Reputation: 57
I'm trying to send the JSON below to a PHP script via the POST method.
{
"operation": {
"name": "Nicolas",
"age": 24,
"sex": "Male",
}
}
What I wanna do is handle the information that is coming from the JSON like name, age, sex, and print unto the PHP response.
How can I do this?
Upvotes: 0
Views: 1772
Reputation: 191
First of all you need to set type: 'POST'
, also a form that will transmit the information.
check this out it might help - http://www.coderslexicon.com/easy-way-to-post-multiple-javascript-values-to-php-using-jquery-ajax/
First Step Is To Package Up Data For Sending
Before we can transport any data we first have to make sure it is in a form that will transmit easily. Since it is easy to create an object in JavaScript out of just about anything, we can start with a simple object literal. We can add our data to it as we see fit and then send it on its way. [...]
// Create an object using an object literal. var ourObj = {}; // Create a string member called "data" and give it a string. // Also create an array of simple object literals for our object. ourObj.data = "Some Data Points"; ourObj.arPoints = [{'x':1, 'y': 2},{'x': 2.3, 'y': 3.3},{'x': -1, 'y': -4}];
[...]
Now For Transmitting This Data In JQuery AJAX
[...] We are going to setup a URL to submit our data to (this would be the PHP script URL we would use like in the action portion of a form), the method which will use (in our case “post”), the data (which will be our JavaScript object we just built) and lastly what to do with the response from the server. [...]
$.ajax({ url: 'process-data.php', type: 'post', data: {"points" : JSON.stringify(ourObj)}, success: function(data) { // Do something with data that came back. } });
Upvotes: 0
Reputation: 2172
This is how I did with AJAX request to send json data to my URL:
var dataToSend = {
name: "Nicolas",
age: 24,
sex: "Male"
}
var jsonDataToSend = JSON.stringify(dataToSend);
$.ajax({
type:'POST',
url: "/your-url",
data: jsonDataToSend,
success:function(data){
console.log("success");
},
error: function (data) {
console.log("error");
}
});
And how to receive this posted data in request handler on PHP side:
$postbody = $request->json()->all();
$name = $postbody['name'];
$age = $postbody['age'];
$sex = $postbody['sex'];
Upvotes: 1
Reputation: 9
If you want to send json data first encode in using json_encode($data). In the php response page call json_decode() to get the response. I hope it helps.
Upvotes: 0