JSON.parse from php script - php

I'm trying to get some JSON from a php script. Bit it is failing when I try to parse it.
In the php script I use json_encode($result) and in the jQuery part I use this code:
complete: function(response){
console.log(response);
var parsed = JSON.parse(response);
var arr = [];
for(var x in parsed){ arr.push(parsed[x]);}
jQuery('#input_1_3').val(arr[1]);
jQuery('#input_1_4').val(arr[2]);
}
When I log response in the console I get this:
Object { readyState=4, responseText="{"personeelsNummer":"1",...oonplaats":"Meerhout"}0", status=200, meer...}
What am I not seeing here?

First things first:
Ensure your $.ajax has dataType: "json" as part of the settings.
$.ajax({
dataType: 'json',
//other settings
});
Second:
You are using complete. On complete, the arguments are jqXHR and textStatus. Therefore, it's not parsed there, it's the entire xhr object.
For that you have to use success. There the arguments are data, textStatus and jqXHR, and if you used the dataType as I told (and your JSON is valid), it data will be your already-parsed json.
$.ajax({
dataType: 'json',
//other settings
success: function(data, textStatus, jqXHR){
//my awesome parsed json it's on 'data'
},
error: function(jqXHR, textStatus, errorThrown){
//my awful json which failed to parse, and I can know the error on 'errorThrown'
}
});

use:
var parsed = JSON.parse(response.responseText);
response is an object with more properties than just the text content from the server request.

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 determine what a PHP page posts back to an AJAX call

I've used ajax quite a bit to send data off to a php page and get something back, but I'm not sure how to determine what specifically gets sent back. I understand what most of the fields here do, but I have a few questions as well.
My current code looks like this:
$.ajax({
url: "search.php",
type: "post",
dataType: "json",
data: {partNumber: q , newType:newType},
success: function(data) {
console.log(data);
}
});
One thing I don't fully understand is how the success: line works. When I say success: function(data), it's my understanding that I'm saying "upon success (of something? I'm not sure what), the information that is returned to this ajax function will be called data," and then inside the brackets, I'm choosing to console.log that data.
Please correct me if I'm wrong in that assumption.
Ultimately, my php page will do a ton of work and return an array with data in it. If the last line of my php code is:
$myArray = array("bob","dan","carl","mike");
how do I choose for that to be returned to ajax? The php page is working fine, but right now my console.log(data) line of code is not returning anything.
You are not supposed to return anything from the php page called by your ajax, you're supposed to echo it (i.e. write it to the response).
echo json_encode($myArray);
And if what you're echoing is not JSon, then take out dataType: "json". The success function means that the request was successful, i.e. a response was received back from the server with status 200. There is also an error method you can use for when you don't get a successful response back.
success: function(data) {
console.log(data);
},
error: function(data) {
console.log("Error: "+data);
}
1) Your on "success" is basically saying when there is not an error that occurs.
Here is testing error
$.ajax({
url: 'search.php',
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
2) For your "data" what you echo on the php side gets returned into the variable defined in your
function(results) {
for example if you want to return an array you may want to return "echo" json
your array should include a key and a value
$myArray = array("key" => "value");
echo json_encode($myArray);
and on the jquery side parse the json object returned.
function(data) {
var obj = jQuery.parseJSON(data);
alert(obj.key);
3) Pass JSON Objects
var JSONObject= {"partNumber":q, "newType":newType};
var jsonData = JSON.parse( JSONObject );
var request = $.ajax({
url: "search.php",
type: "POST",
data: jsonData,
dataType: "json"
});

how jquery ajax fail callback gets triggered if server returns status 200

When PHP's E_FATAL error occurs the server returns the respons with status 200 and responseText: "↵Fatal error: error description. However, the jquery's ajax triggers fail callback instead of done. Why? For the status 200 it should call done callback.
var jQueryDeferred = $.ajax({
method: "post",
url: url,
dataType: "json",
data: data
})
jQueryDeferred.done(function (response) {
if (response.statusCode === 301) {
window.location.assign(response.data || "/");
return;
} else {
customDeffered.resolve(response);
}
}).fail(function (response) {
customDeffered.resolve(response); // THIS CALLBACK IS CALLED
});
the jquery's ajax triggers fail callback instead of done. Why?
Because the expected return type (like json, text, html etc.) is not that which is required.
consider this example:
$.ajax({
url : "your url",
type : "post",
dataType : "json",
success: function(response){
console.log(response);
},
error: function(error){
alert(error.responseText);
}
});
if you return some json object from the specified url then you will get into the success block and that would print the response in the browser's console.
But if there is some error and if it is returning string instead of json then it would go into the error block.
The fail handler is called because you are specifying the response content type as JSON. A PHP fatal error can not be parsed as JSON and so jQuery triggers the fail handler.
var jQueryDeferred = $.ajax({
method: "post",
url: url,
dataType: "json", // <-- here
data: data
})
If you remove the JSON dataType, the success handler will be called instead, but jQuery will not automatically parse the JSON, so you'll have to do it manually.

jQuery AJAX call (POST to PHP) issues

I need to use the $.ajax() call within jQuery to post a little bit of JSON to my PHP script.
I have tried everything but nothing works as I would like it to. I simply try to echo a var_dump of the $_POST/$_GET arrays but it comes back empty.
var myJSONObject = {"bindings": [{"conversation": _conid} ]};
var obj = $.toJSON(myJSONObject);
$.ajax({
type: "POST",
url: "./code/ajax/fetch_messages.php",
data: obj,
async:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data)
{
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
},
beforeSend: function (XMLHttpRequest)
{
},
complete: function (XMLHttpRequest, textStatus)
{
}});
I can see that the post is made by looking in the headers:
{"bindings":[{"conversation":"38x001c61450ad4d5abd47c37408e8236eb5427f54e2930000306882646e4016c5f8ecf8e00a18a26ab3b6d07f6727bd187625daaedf951f93072d54d59e300e100"}]}
PHP:
echo var_dump($_POST);
Everything works great when using the $.post() call but I always run in to problems when I try to switch to $.ajax. I need to use it to be able to retreive the response UTF-8 encoded.
The code pasted in this post is just one of many snippets I've tried, even examples from tutorials on the web does not work.
Could someone please give me a snippet that you know do work so I can try that? Sending JSON through POST.
I think you must give your json string a key, so you can get it on the other side (PHP):
data: {"myjson": obj},
Then on PHP it will be in $_POST['myjson']
below is a slice of my routine and it works fine :
var data = 'post_type=' + post_type.val() + '&page_id=' +
page_id.val() + '&home_page='
+ home_page.attr('checked') + '&archive_page=' +
archive_page.attr('checked') + '&search_page=' +
search_page.attr('checked');
//start the ajax
$.ajax({
//this is the php file that processes the data and send mail
url: "?service=set_data",
//GET method is used
type: "GET",
//pass the data
data: data,
//Do not cache the page
cache: true,
//success
success: function (html) {
$(".no-items").hide("slow");
$("#list_table").append(html).hide().slideDown('slow');
}
});

reading json encoded multiple php arrays using ajax request

I have used json_encode to encode two php arrays and now i have to read through ajax. Could anyone please let me know how to read those arrays through ajax request.
For example: i have a php file file1.php which has
echo json_encode($array1);
echo json_encode($array2);
Another file in which i read as follows:
For reading single encoded array i am reading like this
new Ajax.Request("file1.php",
{
method:'get',
asynchronous:false,
parameters: ({id: stopID, contains: tempContain}),
onSuccess:function(data){
var result=data.responseJSON;
var keys = Object.keys(result);
var values = Object.values(result);
for(var i = 0; i < keys.length; i++) {
infoString += keys[i]+":"+values[i];
}
});
You can use jquery, it will save you a lot of time ;) There are examples in this link:
http://api.jquery.com/jQuery.getJSON/
With jQuery Ajax
$.ajax({
url: '/path/to/file',
type: 'POST',
dataType: 'json',
data: {param1: 'value1'},
complete: function(xhr, textStatus) {
//called when complete
},
success: function(data, textStatus, xhr) {
//called when successful
},
error: function(xhr, textStatus, errorThrown) {
//called when there is an error
}
});

Categories