I recently started translating an old Classic ASP site to PHP. Several of its pages (Response.ContentType = "application/json") would just serve JSON responses such as {"R":1} and everything worked fine.
now on PHP, with header("content-type:application/json") first thing on the code, ajax just will not parse it. The client-side JS code is the same I used before. I haven't even touched it.
$.ajax({
dataType: "json",
type : "POST",
url: "processthisrequest.php",
cache: false,
async: false,
data: { Field1:"bla", Field2:"blabla"},
error: function(data){
// code on error
},
success: function(json){
// code on success
}
});
if the request is accepted ALL it serves is {"R":1} with double-quotes as it's always been.
Ajax will fire the error function no matter what. trying to debug it I found this:
readyState:4
responseText:{"R":1}
status:200
statusText:OK
searching for help I found a lot of people with problems with ajax getting readyState:4, status:200 and the response still not being parsed. none of the solutions worked or applied to my problem.
as it was working with IIS/ASP, can it be something with Apache or PHP?
UPDATE:
still no success, but if I get the server to serve a .js file with {"R":1} instead of processing a response through a php page ajax will fire the success function. which only proves my point that this is a php problem and also explains why it worked with old dinosaur ASP. now why PHP is not serving a proper mime-type is something I am trying to figure out.
I sorted it.
PHP has some very strange ways of doing things.
right after the header("Content-Type: application/json") line I have an include "file.php". although both the file that processes the Ajax request and the include file were saved as Unicode one had BOM signature and the other hadn't.
processing these two files made PHP send "something" back to the browser that was anything but a proper application/json response which wouldn't allow Ajax to parse it.
I know I'm supposed to stay on point here but I am so frustrated I need to add this comment: after wasting almost 18 hours of my life on this, time I could have used working on other things, the only thing I can learn from this experience is that free software is not free at all.
Related
I want to get some JSON data from an URL. I did it successfully with PHP and Guzzle, but my site needs some loading time that's why I want to try the data with AJAX. When I try to get the data with an AJAX-Call, this will happen:
CORS-Header 'Access-Control-Allow-Origin' missing
I googled it and tried things out like adding this header in htaccess and htttp.conf and so on. Nothing changed, always getting this error message.
When I tried to retrieve the data as JSONP, I get the message:
Missing ; before Statement
Googled it too, my question is, is there maybe a way to convert JSON to JSONP while I am getting it via AJAX? Or did someone has another idea to solve the cross origin problem?
EDIT:
Data I want to get: https://www.easports.com/fifa/api/fifa16-ps4/stats/fut/Haggelodeon (maybe you need to hit the url twice to get data)
Ajax call:
$.ajax({
url: "https://www.easports.com/fifa/api/fifa16-ps4/stats/fut/Haggelodeon?callback=?",
dataType: 'jsonp',
success: function(data){
console.log(data);
}
});
I believe this is the code I tried, I deleted it in the meantime so there could be a mistake, especially with the url, I don't know if the callback-part is right from my memory.
I have a php script that I invoke via an ajax call with jQuery:
$.ajax({
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
type: "POST",
url: "getFares.php",
data: someObjectHere,
success: function(data) {
handleSuccess(data);
},
dataType: "json"
});
Most of the time this request works just fine and the server sends the values that I would expect.
Sometimes however, the server just responds with a 303 SEE OTHER response. Nowhere in my php script is anything that could produce this redirect.
Unfortunately I have not been able to find any kind of pattern when the redirect happens. It appears like it only happens when I load the page, then wait for a bit and then invoke the ajax request, but this might be coincidence.
I know this is not a very helpful description but unfortunately I'm stuck here so I'm hoping that someone by luck knows how to fix it.
Here are a couple of screenshots of the dev tools that should illustrate the problem more clearly:
In this image you can see that I've made a couple of request to the script (getFares.php) and I've highlighted one that worked. You can see the status code is 200 and everything is fine.
Here I've highlighted a failed request. The response is 303 See other. As you can see, none of the other values of the request have changed
The only difference in the requests that I have been able to find is seen here. For requests that return the correct result (status 200), the type is "xhr" and for requests that result in the redirect are of type "x-www-form-urlencoded; charset=UTF-8". I don't know why this happens or where it comes from.
I assume the problem could be related to faulty server/php settings but it's difficult to search for this kind of error.
It is not ajax issue but the server itself sending response for some reason.
getFares.php page must be checked for some post parameters, if fulfills, sends 200 response otherwise some other response like 303.
You can check getFares.php code to get more idea.
I'm having a helluva time getting ajax calls and responses to work correctly in IE8 (yes, unfortunately, that's the version my workgroup is stuck on), Firefox, and Chrome.
I have the ajax requests going to a single PHP script on the backend. Because I've experienced strange issues in the past where IE will suddenly complain / behave as if some of our internal/intranet servers are actually "cross-domain", I am making sure the PHP script wraps the data object into a callback function:
echo $callback_name.'('.$jsondata.');';
(However, all the ajax requests from the front-end are passing the same callback name, just to try to keep things simple: jsonpCallback.)
My front-end requests all follow this same format:
$.ajax({
type: 'GET',
url: 'ajax_fetcher.php',
data: { action: 'fetchexecmsg', incident_id: incident_id_number},
dataType: 'jsonp', // doing this because it should avoid cross-domain issues
jsonp:'callback_name',
jsonpCallback: 'jsonpCallback',
success: function(data){
console.log("Ajax call to fetchexecmsg was successful.");
Parse_JSON_object_into_Exec_Msg_Div(data);
}
});
I was doing most building / testing with Chrome. So, today, I decided to test Firefox and IE8.
To my surprise, Firefox was complaining that 'jsonpCallback' wasn't an actual function ??
TypeError: jsonpCallback is not a function (red text in the console)
My understanding was that if I had a "success" function already pre-defined, there'd be no need for that function to actually exist ?
So, I put that in globally as an empty function... and now Firefox is complaining:
Error: jsonpCallback was not called
and this is immediately followed by an ajax parseerror where jqXHR.responseText = undefined.
And I see now that Chrome is logging that parseerror -> undefined as well.
Can anybody provide any guidance on this? I guess my focus right now should be on this 'jsonpCallback' thing. I thought I needed that returned from the backend, so as to "fool" the browser into thinking it was getting Javascript and not data from some remote server.
And then, on the front-end side, I needed to set those jsonp and jsonpCallback variables in the ajax request. But I THOUGHT an actual callback function, as defined with that jsonpCallback variable, was NOT necessary?
Thanks!
-= Dave =-
Dave, remove the "jsonpCallBack" key from the options you setted for jQuery.Ajax.
As seen from http://api.jquery.com/ajax ,
It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling.
I've just moved a site to live and am getting a 406 Not Acceptable error when using jquery to make an ajax request to a php script. I don't get the error on my test server so I'm just trying to figure out the correct way to fix this. The AJAX request is as follows, and expects JSON response, while my php script is just echoing out with json_encode().
$.ajax({
type: "POST",
contentType: "application/json",
data: "{}",
url: "server/php/progress.php",
dataType: "json",
EDIT: here's the crux of my php script (have also tried without the header setting):
header('Content-type: application/json');
echo json_encode($val);
exit;
Any thoughts on what should be done to fix this? htaccess directives?
Not acceptable will be triggered based on Accept, Accept-Charset, Accept-Language headers. So if your code is identical, it's likely that there's some setting related to content negotiation turned on there.
Aargh. Just switching it to GET sorted the issue. I'm not sure why on earth I was using POST for retrieval.
Still not sure why the issue didn't happen on my local wamp server, some difference in the apache settings somewhere.
I have here a test page that should do a jQuery JSONP cross-domain request not once, but twice:
http://www.starcitygames.com/json_test.php
And it should query this here page here to pull up some test data:
http://scg.im/ajax/fetch_recent_URLs.php?callback=fred
After bashing my head against the wall for an entire morning where I got absolutely zero response from this script, pro or con, I put a mail() call in the fetch_recent_URLs script to mail me whenever the remote page was loaded.
It turns out that despite several loadings, tweakings, etc. of the script, it never actually calls the scg.im page. The script isn't broken, returns no fatal errors in JavaScript, et cetera - it just doesn't actually ever seem to fire the AJAX call.
Even more perplexingly, regular JSON calls (to this domain) work fine.
The script(s) are as such:
$.ajax({
url: "http://scg.im/ajax/fetch_recent_URLs.php",
type: "GET",
dataType: "jsonp",
error: function(xhr, status, error) {
alert("error");
},
success: function(json) {
alert("success");
}
});
$.getJSON("http://scg.im/ajax/fetch_recent_URLs.php?callback=?", function(rtndata) {
alert("Returned!");
});
Both are taken from various test pages that claims this works. I've also tried it in jQuery 1.6, changed the header, etc., all encountering the same problem; no matter what I do, jQuery never actually calls the page. (Again, I know this because the script mails me every time it's loaded, and it doesn't email me at all when I load this page.)
Any idea why this is not working? I'm doing, as far as I can tell, everything according to plan (and about five variations on these scripts to boot).
Edit: SOLVED! I figured it out, and it's entirely stupid.
If you have NoScript enabled for FireFox (and you arguably should), AND you have not allowed scripts from the new domain (in this case, scg.im), then NoScript will prevent the domain request before it even begins. Good security. Thoroughly baffling.