How to properly retrieve a JSON string with PHP? - php

I am trying to send a JSON to my PHP script and for some reason is returning null in the alert message.
I've searched throughout Stack Overflow and other forums and used other people's examples but somehow I keep getting it wrong. I checked in Firebug and the request is being sent. I am very new to handling JSON queries.
Could anyone point at what I am doing wrong so that I can learn for the next time?
My JQuery Code:
var name = $('#formName').val();
var regno = $('#formRegNo').val();
var charityinfo = $('#formCharityInfo').val();
var searchimprove = $('#formSearchImprove').val();
var finantialaid = $('#formFinantialAid').val();
var contactname = $('#formContactName').val();
var contactphonenumber = $('#formContactPhoneNumber').val();
var contactfaxnumber = $('#formContactFaxNumber').val();
var contactemail = $('#formContactEmail').val();
var website = $('#formWebsite').val();
var address = $('#formAddress').val();
var postcode = $('#postCode').val();
var arrayData = {"name":name,"regno":regno,"charityinfo":charityinfo,"searchimprove":searchimprove,"finantialaid":finantialaid,"contactname":contactname,"contactphonenumber":contactphonenumber,"contactfaxnumber":contactfaxnumber,"contactemail":contactemail,"website":website,"address":address,"postcode":postcode};
console.log(name);
$.ajax({
url: "test.php",
type: "POST",
dataType: "json",
contentType: "json",
async: false,
data: arrayData,
success : function(response) {
alert(response);
},
error: function(){
alert("error");
}
}); //End AJAX
My PHP Code:
<?php
$return = $_POST;
echo json_decode($return);
?>

first, collect your form data in 1 step, serialize it as json:
var arrayData = $('#my_form_id').serialize();
If you post your data, you should post the appropriate post variable name with it. Add some more decriptive error handling:
$.ajax({
url: "/test.php",
type: "POST",
data: 'mydata = ' + arrayData,
success : function(response) {
alert(response);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
And then on the php side pick it up:
$mydata = $_POST['mydata'];
$arrayData = json_decode($mydata);
var_dump($arrayData);

You haven't encoded the data you are sending as JSON. You are passing an object to jQuery and allowing it to encode it (as application/x-www-form-urlencoded). You need to encode your data as JSON and pass a string to data:.
json is not a content-type, application/json is.
$_POST is populated from application/x-www-form-urlencoded or multipart/form-data, it doesn't contain the raw post request. You need to use php://input to get that.

First of all you don't need to create json yourself
use JSON.stringify() function function to create JSON
or you can also use the jquery serialize() function
var arrayData=$("FORMID").serialize();
$.ajax({
url: "test.php",
type: "POST",
dataType: "json",
contentType: "json",
async: false,
data: arrayData,
.....
and decode this json serverside using json_decode() function

Related

Empty response by JQuery.ajax and object and php

I am stuck by creating my first universal code for ajax responses. I simply do not get an output here, neither in php nor in the ajax response. This must have something to be in the post data.
This is my ajax request:
var info = {};
//get id info
info["ses-id"] = $("#theme").attr("scene");
//get template info
info["ses-template"] = $("#theme").attr("template");
$.ajax({
dataType: "json",
contentType: "application/json; charset=UTF-8",
data: JSON.stringify(info),
type: "POST",
url: "query.php"
}).done(function(data, textStatus, jqXHR) {
alert (data);
//window.location = "?szenen";
console.log("Data sent.");
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log("There was an error." + errorThrown);
});
This is my query.php so far:
<?php
$return = $_POST;
$return["json"] = json_encode($return);
print(json_encode($return));
The output is an object where only the json entry is filled with [].
The stringified variable looks good, it's a string like this:
{"ses-id":"1","ses-template":"2"}
Thanks for any advice!
Your problem is you are sending a json encoded string as the POST body, and then using $_POST to access it. $_POST is an array of key/value POST data. Since your data doesn't have a key, you can't access it from the $_POST array. It's just a value (a string value at that).
If you change your PHP script to be:
<?php
echo file_get_contents("php://input");
?>
It will output the JSON you passed in. Note that there is no need to do a json_encode() because the value is a string, not an array. The json you passed it was never decoded.
Alternatively, if your javascript was:
$.ajax({
data: { "data": JSON.stringify(info) },
type: "POST",
url: "query.php"
})
then your post body would be:
data={"ses-id":"1","ses-template":"2"}
you could then do
<?php
echo $_POST["data"];
?>
Again noting the data you sent it was never decoded, so it's still just a string. PHP does not json_decode for you.
The dataType and contentType both must be deactivated, then I got responses.
$.ajax({
//dataType: "json",
//contentType: "application/json; charset=UTF-8",
data: JSON.stringify(info),
type: "POST",
url: "query.php"
Varying the info object results in varies of the php var but that wasn't my problem.
BIG thanks to everyone especially CJ_Wurtz who pushed me the right way.
It works when you drop contentType and JSON.stringify:
var info = {};
//get id info
info["ses-id"] = $("#theme").attr("scene");
//get template info
info["ses-template"] = $("#theme").attr("template");
$.ajax({
dataType: "json",
data: info,
type: "POST",
url: "query.php"
}).done(function(data, textStatus, jqXHR) {
console.log(data);
//window.location = "?szenen";
console.log("Data sent.");
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log("There was an error." + errorThrown);
});

How to decode a json object sent through jquery ajax method in php file?

This is the jquery ajax part in which i have sent json data to the php file.
$(function () {
$('form').submit(function () {
var fields = $(this).serializeArray();
var ans_json = JSON.stringify(fields);
console.log(ans_json);
$.ajax({
url: "results.php",
type: "POST",
data: ans_json,
dataType: "json",
success: function (result) {
console.log(result);
}
});
return false;
});
});
Now i want to use this json data sent to the php page.How can i do it? I have done it this way but it returns null.
<?php
echo json_decode('ans_json');
?>
I have a set of 10 questions which need to be answered. 3 questions were answered so got the below result.This is what i got in my console.
[{"name":"answer_9","value":"a"},{"name":"answer_10","value":"a"}] quizzes.php:14
null
You don't need to decode any JSON string at server-side if you encode properly your parameters.
You can use .serialize() to do the form serialization for you, and it's ready to send.
$(function () {
$('form').submit(function () {
var serialized = $(this).serialize();
$.ajax({
url: "results.php",
type: "POST",
data: serialized,
...
});
return false;
});
});
Your parameters will be available in your $_POST as in any normal POST request. For example,
$ninth_answer = $_POST["answer_9"];
You need to decode the POST variable. Currently you're decoding just a string which even isn't valid JSON.
<?php
$json_arr = json_decode($_POST['my_json'], true);
var_dump($json_arr);
echo "First name in json is:". $json_arr[0]['name'];
?>
and edit your javascript to reflect following:
This posts my_json parameter with your json as an value. This makes it easy for PHP to recieve it using $_POST.
$.ajax({
url: "results.php",
type: "POST",
data: {"my_json": ans_json},
dataType: "json",
success: function (result) {
console.log(result);
}
});
I suggest to read a little about those things:
http://api.jquery.com/jQuery.ajax/
http://ee1.php.net/manual/en/function.json-decode.php

How to parse json data received from a jQuery ajax call in php

I'm calling a php script (getNum.php) via ajax after creating an object and using jquery.json to turn
it to json. Now i want to handle the object on the php side.
print_r($_POST['data']) doesn't work nor anything else i've tried.
This is my code:
// create object
var bing= new Object();
bing.id = 99;
bing.nameList = getBingList();
//create pdf
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "getNum.php",
dataType: "html",
data: $.toJSON(bing),
success: function(data){
alert(data);
window.location = "generateBing.php?num="+data
}
});
If you're using print_r($_POST['data']) to show the content, you'll need to send it as "data" as well.
$.ajax({
type: "POST",
url: "getNum.php",
data: {data: $.toJSON(bing)},
success: function(data){
alert(data);
window.location = "generateBing.php?num="+data
}
});
Otherwise you have to do print_r($_POST)
Since you are posting a JSON object directly, there is no argument name for $_POST. You'll need to read the raw contents of the POST request. Try this:
$data = json_decode(file_get_contents('php://input'));
print_r($data);

How to send json string to a php file using jquery submit?

*Hi ,
I am very new to using JSON in Jquery. I have a html form which made out using json data and javascript. The Json string is holding the result. Now my question is how to send this string to php file. I am using ajax function for submitting the form *
this is the json string i have
var jsonstr = JSON.stringify(result);
$.ajax({ type:"POST",
url: "ajax.php",
headers: {
'Content-Type': 'application/json',
success: function(){
alert('Test results submitted!');;
Specify the data and dataType options:
var jsonstr = JSON.stringify(result);
$.ajax({
type:"POST",
url: "ajax.php",
data:'json=' + jsonstr,
dataType:'json',
success: function(){
alert('Test results submitted!');
}
});
From php, you can get json string using:
$_POST['json'];

php json_encode not returning proper json encoded string

I am using a jquery ajax call which accepts json response :
var posturl = '/admin/getparamdetails/';
var data = "adnetworkId="+adnetworkId;
$.ajax({
type: "POST",
url: posturl,
data : data,
datatype: "json",
success: function(msg){
//$("#displayPramForm").html(msg);
//alert('hello'+msg.length+' '+msg.hello.length);
console.log(msg);
if(msg!='')
{
alert(msg.hello);
}
},
failure: function(msg){}
});
in my php backend function , I am using json_encode on a simple array as shown:
$json_encoded_string = json_encode(array("hello"=>'abc'));
echo $json_encoded_string;
die;
but alert(msg.hello) returns undefined for me. What is going wrong here ?
Also , in my console.log I am able to get the output as :
{"hello":"abc"}
Use parseJSON on the return data:
if (msg) {
msg = $.parseJSON(msg);
alert(msg.hello);
}
you have to send the data as Content-Type "application/json", otherwise it won't work.
Just add the following in your PHP File:
header('Content-type: application/json');

Categories