2
var formData = new FormData();

formData.append('type', type);
formData.append('description', description);
formData.append('photo', photo);  

var request = new XMLHttpRequest();

request.open('POST', '{{ path('my_webservice') }}');
request.send(formData);

How can I send my FormData using $http?

My main problem with the above code is that I don't know how to generate a callback when the response is received.

So, if I can do it in Angular I'm in more familiar territory.

Thanks

Edit

This seems to work asynchonously. Seems better than any of the Angular solutions suggested in terms of ease of implementation.

                request.onload = function (e) {
                    if (request.readyState == 4 && request.status == 200) {
                        console.log(request.responseText);
                    }
                };
b85411
  • 9,420
  • 15
  • 65
  • 119
  • 1
    I would suggest reading up on angular. Check out $resource and $http. – lintmouse Nov 05 '15 at 05:24
  • I know how to use `$http`, but I'm not sure what to do with `formData`. Every time I've used `$http` in the past I have a JSON object I can pass - in this case I have a `formData`. – b85411 Nov 05 '15 at 05:31

3 Answers3

1

You can use $http to post.

But the content-type has to be changed to application/x-www-form-urlencoded and the data should be serialized using key=value pairs.

These settings should be injected to underlying XMLHttpRequest object of the $http.

Here is an article which shows you how to do that.

Charlie
  • 22,886
  • 11
  • 59
  • 90
  • 1
    It says `This does not use the "multipart/form-data" content type, which is primarily used for form posts that include binary file uploads.`. And `photo` in my initial example is a pointer to a file upload. Will this be a problem for me? – b85411 Nov 05 '15 at 05:39
  • Please experiment with the content-type and see what works for you. I showed you the broad way of how you can use angular to submit form data in conventional format. – Charlie Nov 05 '15 at 05:41
  • Line 51 of the example you link to - the data is a JSON object. How can I include my photo in that given it is a pointer to a file? – b85411 Nov 05 '15 at 05:43
  • You should use FileReader API to read your local file in to a variable and include it in the form data in a suitable format. Here is your reference https://developer.mozilla.org/en/docs/Web/API/FileReader – Charlie Nov 05 '15 at 05:47
  • Due to the nature of the app I'm making, I've had to create a directive such that when the change event of a file input is called I store a pointer to that file in the JSON object (so I can send the Form Data as demonstrated in the first message). – b85411 Nov 05 '15 at 05:53
  • Use the FileReader at that point and read the file data directly instead of the file name. – Charlie Nov 05 '15 at 05:54
  • At what point? When I append the photo to the `formData`? – b85411 Nov 05 '15 at 05:56
  • When the user selects the file. Actually that is the point you can use FileReader. – Charlie Nov 05 '15 at 06:01
  • I've edited the original message with the solution I am using now. I think the Javascript approach seems like a more logical solution in this case. – b85411 Nov 05 '15 at 06:06
  • I answered your original question about using $http for FormData – Charlie Nov 05 '15 at 06:08
0

Add an ng-submit attribute to your form and assign it a function to handle the POST request using the $http service. Angular handles http responses using the promises API. Here is an example from https://docs.angularjs.org/api/ng/service/$http:

$http({
  method: 'GET',
  url: '/someUrl',
  data: { type: 'myType',
          description:'myDescription'
 }
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });
Price
  • 2,683
  • 3
  • 17
  • 43
  • This will encode his form data in json. – Charlie Nov 05 '15 at 05:28
  • @downvoter, What did I miss? – Price Nov 05 '15 at 05:28
  • What's wrong with JSON? How would you do encode data in Javascript? – Price Nov 05 '15 at 05:29
  • This solution doesn't even contain my `formData` object. How do I post that? – b85411 Nov 05 '15 at 05:32
  • You cannot expect a conventional form data phrase to decode data sent through this method. That's what is wrong with it. – Charlie Nov 05 '15 at 05:32
  • Also the question is not about a DOM form which you can include ng-submit to. – Charlie Nov 05 '15 at 05:36
  • Added data to the request body. Maybe @CharlieH can provide a better solution :) – Price Nov 05 '15 at 05:38
  • Please see my answer for the exact (not only better) solution. Your answer is about the general use of $http. The question is about sending form data with $http. – Charlie Nov 05 '15 at 05:39
  • @Price that still doesn't include the photo (pointer to a file upload) though. – b85411 Nov 05 '15 at 05:40
  • Play with the content-type. Do your experiments and find the parameters you should use. I showed you how you should use angular in posting conventional form data. – Charlie Nov 05 '15 at 05:43
  • @b85411, for uploading files, url-encoding of parameters won't work. You would have to use a FormData object and append your files, string data to it. Check this article that explains how to make such a request: http://www.angulartutorial.net/2015/03/file-upload-and-sending-data-to-backend.html – Price Nov 05 '15 at 05:52
0

AngularJS:

$http.post(myRestUrl, {my:"object"}).success(function(data, status, headers, config){/* DO STUFF*/});

Read more at https://docs.angularjs.org/api/ng/service/$http

Or to do it with XMLHttpRequest:

client.onreadystatechange = function() {
  if(this.readyState == 2) {
    print(this.getAllResponseHeaders());
  }
}

http://www.w3.org/TR/XMLHttpRequest/#the-send%28%29-method

John Manko
  • 1,828
  • 27
  • 51