I have a status 200 being returned when I'm using jQuery AJAX. However, I am also getting a syntax error from somewhere. I am posting to PHP like this:
function submit_order(orderInformation) {
$.ajax({
type: 'post',
url: 'queries/submit_order.php?<?=time();?>',
data: 'orderInformation=' + JSON.stringify(orderInformation),
dataType: 'json',
success: function (returnedData) {
console.log(returnedData);
$('#content_container').fadeOut(340, function () {
var new_content = $('#content_container').clone(false);
$('#content_container').remove();
new_content.css('display', 'none');
new_content.children().remove();
new_content.appendTo('body');
$('#content_container').vkTemplate('templates/confirm_template.tmpl?<?=time()?>', returnedData, function (el, data, context) {
console.log('success');
$('#content_container').fadeIn(340);
});
});
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
}
My PHP code is pretty straightforward:
$order_information = json_decode($json_str, true);
//go through the array and make an email out of it
//add a few elements to the array
//send the email
//send back a json string with the added elements
echo json_encode($order_information);
Yet I get this:
And oddly, if I copy paste the JSON string from console.log(JSON.stringify(orderInformation)) into the PHP page:
$json_str = '{"sector_0":{"file":[],"sector_info":{"sector_label":"NIO","purchase_order":"test","proof":false},"lines":{"line_0":{"description":"test","quantity":"2","productId":"1","addressId":"20","shipViaId":"1","notes":false}}}} ';
everything works. What is this error? Where could this < seen in the error be coming from?
Thanks
It is your error handler that gets fired and logs:
xhr.status (200)
thrownError (the syntax error)
Note that $.ajax with dataType: json will fire the error handler even if the server returns 200 OK but the response is invalid JSON. The syntax error is not in your JavaScript code but in the JSON. Identify where the < is coming from and make sure that your PHP script is sending valid JSON.
Tip: open the console and look at the network tab; all XHRs are logged there along with headers and body.
200 - Is an Ok response by a server http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
You have a syntax error in your response server returns invalid json
As your PHP code seams fine, there must be something else. Syntax error or your framework returns json wrapped in html ...
Use proper tools to see what is returned by server. (firebug on firefox/ developer tools on chrome)
In your image you see 0: "<" That means that returned string starts with < - That means it is html that got returned.
Looks like you use chrome. Go to your "network" tab in chrome an you should be able to see raw response for your request.
so it is a php error:
$sector_index is not itarable. Can you var_dump it to see. what it is?
It looks like <?=time()?> isn't getting processed. Alert the URL before you post to it for verification.
Related
I am developing a web app using HTML, PHP and JavaScript. I found a way to call PHP methods that run database operations from the client-side (HTML and JS) using AJAX, here's an example:
if (confirm('Sure you want to do that?')) {
$.ajax({
url: "myScripts.php",
type: "POST",
data: {
paramForOperation: myParam,
option: "doAction1"
},
cache: false,
success: function(response) {
//Here I reload or load another page after server is done
window.open("myPage.php", "_self");
}
});
}
So here I call the php file with the script that does an INSERT/ DELETE / WHATEVER on the database. It works fine, but what if I couldn't insert because the index already exists or any other reason? What if some type of data is wrong and I can't insert it? I know I can validate that on the server side using PHP, but how do I return a message saying "Operation complete" or "You should use numbers on X field"?
I thought of something like alert(response); but what will it return? An echo($msg); from my PHP functions? Is there a way to send the result message on that response thing in AJAX?
Thank you for your help.
Any output of the PHP script will be received in response. Remember, the PHP script runs on the server and just generates output. The PHP code itself never reaches the client.
So, you can just echo a message, and alert it in Response.
Bringing it up a notch, you can return a small piece of JSON or XML that can be parsed and which can contain an error message and some error code, so you script can also respond to that, and maybe change its behaviour (if the insert succeeded, add the new data to the page, for instance).
And of course, instead of returning always code 200 (meaning OKAY) from PHP, you could consider returning other HTTP status codes, so the code already indicates whether something went wrong or not. Depending on the status code, jQuery will execute either the success or the error handler, so it's easy to make different handlers for different situation.
Let your server respond with appropriate HTTP Status Codes and meaningful error messages. Use the error function of the ajax call.
$.ajax({
url: "myScripts.php",
type: "POST",
data: {},
success: function(response) {
/* no error occured, do stuff... */
}
error: function(jqXHR, textStatus, errorThrown) {
/* handle the error, add custom error messages to any DOM objects, ... */
console.log(textStatus, errorThrown);
}
Some docs: $.ajax and HTTP Status Codes
I want to execute the following AJAX call (cross domain):
$.ajax({
type: 'GET',
url: url + "?callback=?",
contentType: 'application/json',
async: false,
jsonp: "callback",
dataType: 'jsonp',
success: function (json) {
alert("ok" + JSON.stringify(json));
},
error: function (json) {
alert("err" + JSON.stringify(json));
}
});
And I am getting this alert message:
err{"readyState":4,"status":200,"statusText":"success"}
Which means the code ends in the error method.
If I check the request in Firefox or Chrome, the JSON part of the response is available and clearly formatted. Is it possible to get the JSON response in the error method? Or do you have any idea why the success method isn't hit?
It's not my server unfortunately, so I can't implement any changes on the server side. I used http://jsonlint.com/ to validate the JSON output and it is Valid. Entering the same URL in the browser returns the JSON content correctly.
Thanks much in advance,
I tried a few different approaches, but still failing on the error method,
[EDIT]
SO, I am playing with different approaches, always getting the same error. If I change the error part of my call to this:
error: function (jqXHR, textStatus, ex) {
console.log(arguments);
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
Then I am getting the following error:
http://i.stack.imgur.com/ck6Sd.png
Copy paste of error for search engines:
0: Object
1: "parsererror"
2: Error
message: "jQuery11020553141210693866_1392367304225 was not called"
stack: (...)
get stack: function () { [native code] }
set stack: function () { [native code] }
proto: d
callee: function (jqXHR, textStatus, ex) {
length: 3
proto: Object
The same things apply as above, the response is readable in the browser without issues.
EDIT2
I ended up doing the JSON call the old way, embedding it into the page:
script = document.createElement("script");
script.type = "text/javascript";
script.id = "resultJSON";
script.src = url;
$(".resultsOutput").append(script);
But I have troubles retrieving the data, the script tag seems to be empty. I am getting an error on the JSON:
Uncaught SyntaxError: Unexpected token :
Anyone able to help? I am starting to get desperate on this one. It seems that the issue is that the JASON is returned without a method wrapper.
[LAST EDIT]
So, turns out the server doesn't support CORS and the returned JSON isn't wrapped in a JS function, so this approach won't work. I'll have to use some other approach to retrieve the data.. thanks everyone for reading
Andy
Is there any particular reason to:
Override random callback name jquery gives?
Set datatype to application/json?
This second one may be causing the error. If I'm correct, the server would return application/javascript mime-type, since it should return the JSON you are looking for wrapped into a callback function that shall be called once the request hast completed. Something like this:
function callback() {
return {"a","b"} //the JSON you are looking for
}
This all is handled internally by creating a tag "script" to avoid cross-domain browser restrictions, so you cannot handle JSON directly, it needs to be wrapped into Javascript code. Thus, contentType may be wrong.
Try removing the contenType property on the ajax options and see how jquery behaves (it should interpret content-type from response headers from the server).
I have this response coming from a ASP.NET web service
<string xmlns="http://Walkthrough/XmlWebServices/">
{"approverName":"","emailAddress":"","companyName":"ABC","address":{"streetAddress1":"12 BlahBlah","streetAddress2":"","state":"ON","zipCode":"","country":"SO","phoneNumber":""},"tabledata:"[{"vendorPart":"AAAAA","partDescription":"N/A","price":"0.00","quantity":"28"},{"vendorPart":"BBBBBBB","partDescription":"N/A","price":"0.00","quantity":"3"},{"vendorPart":"CCCCCC","partDescription":"N/A","price":"0.00","quantity":"25"}]}
</string>
which is being called with this jquery function:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "http://www.webservice.com/blahblah.asmx/blahb123",
data: "tnWsGuid=TEST1",
dataType: "script",
success: function(msg)
{
alert("sucess")
},
error: function(e)
{
alert(JSON.stringify(e));
}
});
});
My first question is this, I was having 403 forbidden issues with this function but omitting the contentType changed that. Then I was getting XML parsing issue and on a whim changing the dataType to script fixed that and gave me a response and I hit the success function. Why did that work?
I also would like to know how I can print out this data, because trying to treat it as json won't work, neither does XML.
In chrome I receive this warning:
Resource interpreted as Script but transferred with MIME type text/xml: "http://www.webservice.com/blahblah.asmx/blahb123?tnWsGuid=TEST1&_=1366025879568."
The part appended to the end of this url is confusing me (after TEST1).
In the console I also get this error in chrome:
Uncaught SyntaxError: Unexpected token <
Firebug gives me:
SyntaxError: syntax error
[Break On This Error]
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://Walkthrough/XmlWebServices/">
{"approverName":"","emailAddress":"","companyName":"ABC","address":{"streetAddress1":"12 BlahBlah","streetAddress2":"","state":"ON","zipCode":"","country":"SO","phoneNumber":""},"tabledata:"[{"vendorPart":"AAAAA","partDescription":"N/A","price":"0.00","quantity":"28"},{"vendorPart":"BBBBBBB","partDescription":"N/A","price":"0.00","quantity":"3"},{"vendorPart":"CCCCCC","partDescription":"N/A","price":"0.00","quantity":"25"}]}
</string>
So basically now that the dataType is script I get some sort of response but still have no idea how to parse this data. Preferably into a html table.
I hope you can help! Thanks for reading!
Edit:
Here is a link to the header information logged by Firebug here
your need to set datatype to json as the server send a json array.
see the datatype section here http://api.jquery.com/jQuery.ajax/
I have fixed this issue and successfully have it working on IE returning the dataset (not yet working on Chrome and Firefox due to the asynchronous problem with the two which I hope will be fixed when hosting this page. I added $.support.cors = true; right before the ajax function and my new success function properly show's the data like so:
function(data, status, jqxhr) {
xmlString = data;
alert(xmlString);
}
I have an issue with jQuery 1.7.2 and the ajax function, in that when I call the code below I get the following error in Firefox Firebug console:
NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments
[nsIDOMLocation.replace]
var weights= new Object();
// weight is then manipulated in here
$.ajax(
{
url: '/admin/countries/index.php',
data: ({action: 'sort', cid: cid, weights: weights}),
dataType: 'json',
success: function(data){
alert('suck-sess');
// do stuff in here
},
error: function (request, status, error) {
alert(request.responseText);
}
}
)
I'm not even certain that it's successfuly making the request as when I dump out $_REQUEST["action"] in my index.php PHP it comes through blank, when it should clearly be 'sort'.
When I execute the code I don't get the success or error alert, so I can't see where the error is coming from.
NS_ERROR_XPC_NOT_ENOUGH_ARGS: Not enough arguments [nsIDOMLocation.replace]
This is the kind of internal errors thrown by gecko based browsers (firefox). I don't think it's related to your code. Seems to me more like a browser bug.
It turned out that weights was the problem, as you can see it was defined as a JavaScript object, however I had to use JSON.stringify(weights) to pass it through as a JSON-encoded string.
The following javascript code gives me ">success-<", i.e. empty data. Pasting the url in my browser gives me the expected content.
$.get("http://company.tld/wiki/api.php?action=query&titles=Page%20Title&format=xml&prop=revisions&rvprop=content", function (data, status) {
alert(">" + status + "-" + data + "<");
});
It's a MediaWiki wiki. Here's the MediaWiki API specification: http://www.mediawiki.org/wiki/API:Query
Why am I not getting any data?
You might breach the ajax cross domain policy there.
Is that domain you try to access yours? better said, the one from your script?
From my experience, if you try to access data from a foreign domain, the success handler will fire regardless. But as you describe, with no data at all.
If data is an object you will receive the close results. Try use typeof data in the alert.
UPDATED:
To jAndy: In the documentation of jQuery.ajax we can read following (see http://docs.jquery.com/Ajax_Events):
success (Local Event).
This event is only called if the request was successful (no errors from the server, no errors with the data).
I just tried execute the following code
try {
$.ajax({url:"http://en.wikipedia.org/w/api.php?action=query&titles=jQuery&format=xml&prop=revisions&rvprop=content",
success: function (data, status, x) {
alert ("ok");
},
error: function (data, status, x) {
alert ("not ok");
},
dataType:"xml"});
} catch (e) {
alert ("exception");
};
where I try to use a crossdomain call. In IE I can see "exception" alert. In Chrome and Firefox: "not ok". The function success will NOT be called in case of error.
So the data from server are really an empty string ("") for the url of Tobbe.
To Tobbe: you should add the last parameter "xml" probably.