I had passed the json string through ajax in jquery like this. My JSON file has check boxes and list values.
var jsonstr = JSON.stringify(result);
here 'jsonstr' is the selected form elements.
function runAjax(jsonstr)
{
type:"POST",
url: "ajax.php",
data: 'json=' +jsonstr,
dataType: 'json',
headers: {
'Content-Type': 'application/json',
success: function(){
alert('Test results submitted!');
},
};
return false;
In php I am trying to recieve the JSON stringlike this, but it was giving the output like "null".
$data= $_POST['json'];
//decode Json string to PHP object
$phpobj = json_decode($data,true);
print_r($data);
$phpobj = json_encode($data,true);
Is there anything wrong I am doing and and what should be in decoding part? Can anyone help?
If you want to send it as json string, please give like this
data: {json:jsonstr}
so it should be
$.ajax({
type : 'POST',
url : 'sample2.php',
data: {json:jsonstr},
success : function(data){
alert(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("error");
}
});
It should work for you.
Actually there is no need to convert the object to json. You can directly give it in $.ajax .
var data = {name:"Jack", age:12, place:"CA", marks:70};
$.ajax({
type : 'POST',
url : 'post.php',
data: data,
success : function(data){
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
}
});
and in php you can read like
$_POST['name']
$_POST['age']
$_POST['place']
$_POST['marks']
Please check the value of $_POST['json']. It should contain something like {"a":"aaa", "b":"bbbb"}.
Check section "Example #3 common mistakes using json_decode()" here http://php.net/manual/en/function.json-decode.php
You can try the following:
In Javascript change
var jsonstr = JSON.stringify(result);
and
data: 'json=' +jsonstr,
to a simple
data: JSON.stringify({json: result}),
.
In PHP read data instead of this way
$data= $_POST['json'];
in this one
$data=json_decode(stripslashes(file_get_contents('php://input')));
Once done that, access your data in this way:
$data->{'variable-name'}
You're very lucky, I understand this question
var jsonObject = eval("(" + jsonFormat + ")");
Related
My code returns dataType object in PHP but when I am calling the same function using AJAX it returns the datatype to me as string. I want the data type to be a JSON object.
PHP code:
$result = $manualRequest->getUser($_POST['phonenumber']);
print_r($result);
This is actually a parsed database object
AJAX code:
function getCustomer() {
var callerNumber = $('#caller_number').val();
var data = {
'phonenumber': callerNumber
};
var url = "customerRequest.php";
$.ajax({
url: url,
data: data,
type: 'POST',
dataType: 'JSON',
success: function (result) {
console.log(result);
}
});
}
I am getting the desired result but I want the JSON object and not the string.
print_r doesn't generally return valid JSON, you want to do
$result = $manualRequest->getUser($_POST['phonenumber']);
echo json_encode( $result );
As long as it's valid JSON, and the dataType is set to json, jQuery will parse it as such, anything else should result in a "parse error" in your ajax request.
In javascript you can use JSON.parse method to parse your string JSON to JSON object.
The documentation of this method: https://www.w3schools.com/js/js_json_parse.asp
In php file add:
header('Content-type:application/json;charset=utf-8');
echo json_encode($result);
instead of print_r($result);
If you want pretty JSON
$result = $manualRequest->getUser($_POST['phonenumber']);
echo json_encode($result , JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT );
Edit
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: data,
success: function (response) {
console.log(response);
}
})
.done(function () {
console.log("success");
})
.fail(function () {
console.log("error");
})
.always(function () {
console.log("complete");
});
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);
});
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
I seem to have trouble with getting data from a php array, I've looked at various examples of how to do this but I must be missing something because I can not get my code to work.
PHP method
function getLatestActivity(){
$messages = array(
array('id'=>'01', 'value'=>'blah'),
array('id'=>'02', 'value'=>'Oil'),
array('id'=>'03', 'value'=>'Spark')
);
echo json_encode($messages);
return;
}
AJAX get functiom
function getLatestActivities(){
$.ajax({
type: "GET", url: "include/process.php",
data:{
getLatestActivity: "true",
toUser: "4",
ignoreMessages:"1",
dataType: "json"
},
success: function(data){
$.each(data, function (i, elem) {
alert(data.id);
});
}
});
}
The alert prints out the message "undefined", any help would be appreciated thank you.
Try with - it's your single object now:
alert(elem.id);
It is quite likely that data isn't what you're expecting. You aren't setting any headers in your response, and as hinted at by #Sudesh dataType isn't in the right place. The result is that data is most likely a string because jquery will not parse it as json.
You're also referring to the wrong variable. data.id cannot exist with the data you are returning from php. you would need elem.id or if you prefer data[i].id if data did contain what you're expecting. As an aside - using $.each instead of a for loop is relatively inefficient.
You can check if that's the case with code such as:
function getLatestActivities(){
$.ajax({
type: "GET", url: "include/process.php",
data:{
getLatestActivity: "true",
toUser: "4",
ignoreMessages:"1",
dataType: "json"
},
success: function(data){
console.log(data); // <- look at the response
$.each(data, function (i, elem) {
// alert(data.id); don't debug using alerts
console.log(elem);
});
}
});
}
If data is a string (or simply, not what you're expecting) this should get you closer:
function getLatestActivity(){
....
header('Content-type: application/json');
echo json_encode($messages);
}
with
function getLatestActivities(){
$.ajax({
url: "include/process.php",
data:{
getLatestActivity: true,
toUser: 4,
ignoreMessages:1,
},
success: function(data){
console.log(data);
...
}
});
}
data should at least then be an array.
I think dataType should not be part of data object rather should be sibling of success (options). I believe you are not getting data as JSON object rather just string because of it
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');