I need to save a json object to a file.
Therefore I'm using another PHP script which writes the data to a file. Data and filename are sent by an ajax POST request.
var results = $('results');
var filename = $('#filename').val();
$.ajax({
url: 'jsonWriter.php',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify([{data: data, filename: filename }]),
success: function(data) {
results.html(data);
},
error: function(jqXhr, textStatus, error) {
results.html("<p class=\"error\">ERROR: " + textStatus + ", " + error + "</p>");
}
});
When I monitor the request in Fiddler, it looks fine and the posted data is correct.
However, somehow the error function is invoked. It outputs
ERROR: parsererror, SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
I copied the posted JSON data from Fiddler into different online parsers, which ensured it is valid.
Why is the error function invoked anyway?
It looks to me like you are expecting the server to return text content, since you are applying it with .html:
success: function(data) {
results.html(data);
},
However, you are telling jQuery to expect JSON data:
dataType: "json",
jQuery is therefore attempting to parse your content returned from the server as JSON and failing. You need to change dataType to either text or html.
Related
I am working on saving the query results from mysql in an array from php and sending the array to the client in json form.
All the character sets, including mysql character set, are utf8, and after checking the results after json_encode(), an invalid json string came out.
$final_result = json_encode($result, JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_IGNORE | JSON_INVALID_UTF8_SUBSTITUTE);
echo $final_result; // == valid json data
After checking using the json validator, I found that a valid json data was created.
However, after the echo call, I received the data from the client to ajax and checked it, and the following error occurred, so I cannot parse it.
SyntaxError: Unexpected token in JSON at position 64362
at parse (<anonymous>)
at jquery.min.js:2
at l (jquery.min.js:2)
at XMLHttpRequest.<anonymous> (jquery.min.js:2)
lastime":"2020-03-19 08:55:10�����"
As a result of checking, the characters shown in the picture were created in the middle, so the parsing is not working.
$.ajax({
url: 'test.php',
data: {action: 'get_Data'},
type: 'post',
dataType: 'json'
}).done(function (json_text) {
alert("done");
console.log(json_text);
json_Obj = JSON.parse(json_text);
console.log(json_Obj);
}).fail(function (xhr, status, errorThrown) {
alert("fail");
console.log(xhr);
console.log(xhr.responseText);
console.log(status);
console.log(errorThrown);
});
Of course, I declared the data type json at the place where I called Ajax Post.
I don't know why well-encoded data in php-side is called jquery, ajax on the client side, and why the following happens.
Can you tell me what I missed?
This js jQuery script is properly formatting the form data to an object and sending it to my PHP code.
$("#formSignup").submit(function(e){
// Map the array into a properly formatted object
var data = {};
$.map($(this).serializeArray(),function(n, i){
data[n.name] = n.value;
});
// Send the http request
$.ajax({
type: "POST",
url: "api/signup.php",
data: JSON.stringify(data),
contentType: "application/json",
success: function(response){
//console.log(JSON.parse(response));
console.log(response);
},
failure: function(err){
console.error(err);
}
});
e.preventDefault(); // Don't submit defaultly
});
However PHP is unable to receiving the data. print_r($_POST) will print an empty array and the values are not accessible. It's not getting a response from the wrong file either.
That is pretty weird considering that the XmlHttpRequest recorded by the mozilla dev console is clearly posting the JSON data.
Other questions have been answered by stating redirects made by the server. However I haven't done anything at all with these settings and I got post requests working on the same server with my own function a while back.
Remove contentType property from your ajax object.
To serialize data just use $(this).serialize().
$("#formSignup").submit(function(e){
var data = $(this).serialize();
// Send the http request
$.ajax({
type: "POST",
url: "api/signup.php",
data: data,
success: function(response){
console.log(response);
},
failure: function(err){
console.error(err);
}
});
e.preventDefault(); // Don't submit defaultly
});
After that you should be able to successfully see your data inside $_POST variable.
What I'm doing is returning an RSS feed obtained via a PHP cURL. I return $returnedData which is an associative array that looks something like this:
array(2){
["lastupdate"] => string(29) "Tue, 11 Feb 2014 15:25:42 GMT"
["feed"] => array(20) {
<items contained within ["feed"][0] to ["feed"][19] (very large)>
}
}
I tried to run a json_encode before returning it to Ajax, but all it essentially did was convert my array into one large string. My Ajax is as follows:
$.ajaxSetup ({
cache: false
});
request = $.ajax ({
type: "GET",
url: "dataFetcher.php",
data: arg,
});
request.done(function(response){
var resultsArray = response;
$("#message").text(resultsArray);
});
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
The thing is, I don't exactly know what I'm getting. If I do var_dump($returnedData) instead of return $returnedData I know that I get a string. But if I simply return $returnedData, I can't tell what Ajax is receiving. I tried changing the text displayed by using resultsArray[0] or resultsArray[1] or resultsArray["lastupdate"] hoping that it worked, but it didn't.
Would really appreciate it if someone could shed some light on what I'm not doing/what I'm doing wrong here.
Thanks!
AJAX receives the response sent by the server. I'm not a PHP programmer, but from what I've picked up reading other SO questions, you'd need to do something like:
echo json_encode($returnedData)
in your PHP script. The echo means that it's part of the output, and json_encode converts your PHP array into a JSON string, which represents the array in a way that JavaScript actually understands.
Depending on the headers of the response set in your PHP jQuery may or may not automatically parse the string as JSON, passing the resulting object/array to the success handler (as the value of the first argument) rather than just passing along the string response. You can tell it to do that (if you know the response will/should be JSON) by setting the dataType property in your $.ajax() call:
request = $.ajax ({
type: "GET",
url: "dataFetcher.php",
data: arg,
dataType: 'json'
});
Then inside your done handler function response would be the JavaScript object that matches your PHP array.
Two things:
Use json_encode in your PHP script to encode the data.
jQuery is interpreting the response as a string. You can either parse the response string as JSON, or you can take the easier route of setting the AJAX request to expect JSON.
So:
request = $.ajax ({
type: "GET",
url: "dataFetcher.php",
data: arg,
dataType: 'json' // <--- Your response parameter will be in JSON format by default, now.
});
You need to eval your response to javascript object
request.done(function(response){
var resultsArray = response.evalJSON();
$("#message").text(resultsArray);
});
or inside ajax call define that you will receive json
request = $.ajax ({
type: "GET",
url: "dataFetcher.php",
data: arg,
dataType: 'json'
});
I need a jsonp response from cross domain url. My jsonp code is here
$.ajax({
dataType: 'jsonp',
async: false,
contentType: "application/json",
jsonpCallback: "domaincheck",
data:{
id:k,
domain:l
},
url: 'http://example.com/param',
success: function (data) {
console.log(JSON.stringify(data));
},
In the php file, the output is like this:
<?php
echo $_GET['callback']."([Correct])";
?>
I knew that the data what I am returning back is incorrect. Because I think we should pass response as json data only. But in this case, sending only "correct" as response, how should we set it, so that we get the response correctly.
The error what I get in console is this:
Uncaught SyntaxError: Unexpected identifier
I'm trying to post data via ajax, this is my info:
var jsondata =
{"address" : [
{ "id": addid, "streetaddress": streetaddress, "city": city, "state": state, "zipcode": zipcode, "latitude": latitude},
]
};
var jsontosend = JSON.stringify(jsondata, null, 2);
ajax function:
$.ajax({
type: "POST",
url: "process.php",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
data: jsontosend,
success: function(msg){
alert(msg);
}
});
return false;
alert('Data sent');
}
on the php end, when i print_r($_POST) it just says
array(0) {
}
I'm alerting (jsontosend) and its showing me everything perfectly, as well as in firebug using post mothod, its showing all the params sent in a perfect clean manner.
The only way it passes any data is if I use GET method.
Any advice is greatly appreciated!
EDIT: adding POST data from firebug.
this is whats being alerted from the alert function:
{"address":[{"id":1473294,"streetaddress":"3784 Howard Ave","city":"Washington DC","state":"DC","zipcode":20895,"latitude":39.027820587}]}
this is what firebug is showing as whats being passed when using POST method:
myData=%7B%0A++++%22address%22%3A+%5B%0A++++++++%7B%0A++++++++++++%22id%22%3A+76076%2C%0A++++++++++++%22streetaddress%22%3A+%223784+Howard+Ave%22%2C%0A++++++++++++%22city%22%3A+%22Washington+DC%22%2C%0A++++++++++++%22state%22%3A+%22DC%22%2C%0A++++++++++++%22zipcode%22%3A+20895%2C%0A++++++++++++%22latitude%22%3A+39.027820587%0A++++++++%7D%0A++++%5D%0A%7D
and this is the response for var_dump of $_POST:
array(0) {
}
this is a var_dump of $_POST['myData']
NULL
I'm skeptical of the way you're using the contentType property. Try taking out contentType. The default content type is
application/x-www-form-urlencoded (http://api.jquery.com/jQuery.ajax/).
Also, use something like {mydata: jsontosend} for your data property.
$.ajax({
type: "POST",
url: "process.php",
//contentType: "application/json; charset=utf-8",
dataType: "JSON",
data: {mydata: jsontosend},
success: function(msg){
alert(msg);
}
});
Use
data:{myData: jsontosend}
It should send myData as a parameter in your request.
PHP doesn't understand application/json requests (by default).
See this question: How to post JSON to PHP with curl
I found that the comment provided by dkulkarni was the best solution here. It is necessary to read directly from the input stream to get POST data of any complexity. Changing the value of $.ajax({contentType: ''}) did not work for me..
In order to troubleshoot this problem I had set up a controller method to echo back the JSON I was posting to my server. Changing the ContentType header made no difference.
But after reading dkulkarni's comment I changed my server code from this:
return $_POST;
to this:
$data = file_get_contents('php://input');
return json_decode($data);
It worked perfectly.
As dkulkarni commented in his post (Jan 24 at 7:53), the only way to retrieve JSON sent with Content-Type application/json seems to be to retrieve it directly from the input stream.
I made a lot of tests with different approaches, but always when I set Content-Type to JSON, the $_POST in PHP is empty.
My problem is I need to set Content-Type to JSON, because the server (where I don't have access) expects it, otherwise it returns unsupported datatype. I suppose they are retrieving directly from input stream.
Why I have to reproduce that in own PHP file? Because I need to make a proxy for testing issues, but thats not the point of this thread.
Taking contentType out is not a good idea. You DO want to send this data in JSON format. Key is to do what has been mentioned above, instead of trying to access the data on the receiving end (the target php file) with $data= $_POST it is critical to use $data = file_get_contents('php://input');
Here is an example of the entire round trip for a scenario with php and knockout.js:
JS (on requesting page):
function() {
var payload = ko.toJSON({ YOUR KNOCKOUT OBJECT });
jQuery.ajax({
url: 'target.php',
type: "POST",
data: payload,
datatype: "json",
processData: false,
contentType: "application/json; charset=utf-8",
success: function (result) {
alert(result);
}
});
};
And then in target.php (the page receiving the request):
$data = file_get_contents('php://input');
$payload_jsonDecoded = json_decode($data
Try removing ' dataType: "JSON" ' from the ajax request and check.