RSSD RSSD - 6 months ago 11
AngularJS Question

AngularJS post method is not working

I'm trying to sends some data along with a post to a specific url which has a php script behind it. At this moment I don't have access to the php script. The php script checks if the string matches any record in the db and returns that record if there is a match. If there is no match the script will return all the records.

The following code is what I have so far. As you can see I have a string
named: shouldnotfindanyresultsstring. This should actually not return any results. However it returns all records instead of no records.

What I tried:


  • Use
    params
    instead of
    data

  • use different
    Content-types

  • use the short version of the post method






$http({
url: $scope.url,
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {search: "shouldnotfindanyresultsstring"}
}).then(function (response) {
console.log(response);
}, function (response) { // optional
console.log("Still not working");
});


So eventually I want to search records in the db with the search string. However I do not get it working.

With postman I can generate a post which works. I do have a strong feeling that it has something to do with the
Content-type

Answer

If you want to use 'application/x-www-form-urlencoded' then format your data as a string

data: "search=shouldnotfindanyresultsstring"

If you want to use 'application/json' then use this:

var jsonData = { search : "shouldnotfindanyresultsstring" };

$http({
    method: 'POST',
    url: $scope.url,
    contentType: 'application/json',
    data: JSON.stringify(jsonData),
}).
    success(function (data) {
        console.log(data);
    }).
    error(function (message, status) {
        console.log(message);
    });
Comments