Reputation: 1439
Using a normal html form, I can add a new task by sending POST request to /api/tasks/insert/ POST data includes $name and $description of the task. However, when I use Angular to push the data to REST API in php, only a POST request is sent and an empty row is created in the database. This means that the POST variables are not being passed i.e. name and description. What am I doing wrong?
I have been stuck at this for the last few hours now. I have checked countless tutorials and am pretty sure of the syntax. My backend REST api in PHP works fine.
var res=$resource('http://localhost/api/tasks/insert/',{},
{
createTask:{method:'POST'}
});
postData={name:"Hello",description:"DescBaby"}
res.createTask({},postData);
//res.createTask(postData); tried this also, but doesn't work
Another variation that I tried based on an comment was this:
res.createTask({name:"TestName", description:"descBaby"}).$promise.then(function(value)
{
console.log("Success"); //I get success in console.
},function(errResponse)
{
console.log("Error");
});
Angular Does not give me any errors. Just sends a blank POST request to the url.
EDIT: I checked in the network pane in Chrome whether the data was sent or not and as it turns out it is being sent. However, in the response it's showing this :
Undefined index: name in XYZ.php line ABC.
The line pointed above is the following line in my PHP:
$obj->InsertTask($_POST['name'],$_POST['description']);
Upvotes: 2
Views: 345
Reputation: 1439
Thanks to a friend of mine, I finally got the code running. The problem wasn't with my Angualar Code but with php code.
As it turns out I cannot read POST data as $_POST[]. file_get_contents should be used in such cases as data is sent through a JSON payload and not through request parameters!
Here's how I got it running : Angularjs $http.post, passing array to PHP
Upvotes: 1
Reputation: 4882
Try this (and create a factory to follow the best practices):
Service
services.factory("Tasks", function($resource) {
return $resource('http://localhost/api/tasks/insert/', {}, {
createTask: {method:'POST', params: {name:"Hello",description:"DescBaby"}}
})
});
Controller
Tasks.$createTask();
Upvotes: 0
Reputation: 70
Did you look at the network tab of debugger? You can check if valid data was sent to server. If it was ok this is not JS or Angular question. On the first look it seems that you have valid code for angular. Just in case check if you have set proper ajax headers.
"X-Requested-With": "XMLHttpRequest"
Does other AJAX calls work for you?
Upvotes: 0