Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular $http POST to target="_blank"

I need to make a POST from Angular to a URL ./makeFile.php which will create a file with contents from a database query based on the information provided in that POST data.

PHP forces the browser to open a save dialog rather than just displaying the response with these 2 lines:

header('Content-Disposition: attachment; filename="' . $file_name . '.prj"');
echo $json;

But making a POST from AngularJS using $http forces the browser to not open this save dialog:

   $http({
      method: 'POST',
      url: './makeFile.php',
      data: {
        project: ProjectService.getProject()
      }
    })

I can't make a GET because the data is too long for a URL, otherwise I would replace it with a simple $window.open('./makeFile.php', '_blank') which works in (the rare) case of small data.

How do I make Angular make this POST to another window or let the browser open the save dialog?

Edit:

As Ivan suggested, I had to programatically create a form to achieve what I want. Here's how I did it:

JavaScript:

    var form = document.createElement('form');
    form.action = './php/saveProject.php';
    form.method = 'POST';
    form.target = '_blank';
    form.style.display = 'none';

    var input = document.createElement('input');
    input.type = 'text';
    input.name = 'project';
    input.value = angular.toJson(ProjectService.getProject(), false);

    var submit = document.createElement('input');
    submit.type = 'submit';
    submit.id = 'submitProject';

    form.appendChild(input);
    form.appendChild(submit);
    document.body.appendChild(form);

    $('#submitProject').click();

    document.body.removeChild(form);

PHP:

<?php
        $project = get_magic_quotes_gpc() ? stripslashes($_POST['project']) : $_POST['project'];

        // ...

        header('Content-Disposition: attachment; filename="' . $file_name . '.prj"');

        echo $json;

?>
like image 957
Bruno Finger Avatar asked Apr 23 '15 12:04

Bruno Finger


1 Answers

I had similar issue, and I couldn't do with with $http. So I programatically created html form with method="post" and target="_blank". And I placed hidden elements with data I needed to send. After I submitted that form I removed it from dom.

Let me know if you find another solution, using $http.

like image 153
Ivan Toncev Avatar answered Sep 21 '22 11:09

Ivan Toncev