This is my $.ajax function. volunteerDist is an array in a previous function and it calls myAjax(volunteerDis);However, the program always calls the error and complete functions, with an error message of undefined. What should I do? Thanks
admin-view-available-volunteeers.php is the filename where this is located
volunteerDist is an array that contains floats
function myAjax(volunteerDist){
$.ajax({
type:'POST',
url: 'admin-view-available-volunteeers.php',
data : ({
distance:volunteerDist
}),
success: function(){
alert('worked');
},
error :function(err){
alert('nope :( ERROR: ' + err.ErrorMessage);
},
complete : function(){
alert('thanks');
}
});
}
If your error: handler is being called, then the remote script returned an error.
Fix the script, not the JS code!
To get better debugging on error you need to update your code, this
error :function(err){
alert('nope :( ERROR: ' + err.ErrorMessage);
},
will not work - as err is a jqXHR object!
change it to this :
error: function(jqXHR, textStatus, errorThrown) {
alert("Error : " + errorThrown);
}
This will output the message sent by the server.
All the details for the params of .ajax() are documentation here
Update
Check the name of your PHP file ...
admin-view-available-volunteeers.php
has 3 es in the word volunteer ... is this the problem ?
I always get this a lot. In your admin-view-available-volunteers.php you need to make sure that you're outputting the right headers.
To do that you need to put this in your php before anything is output:
header("HTTP/1.01 200 OK");
header("Content-type: text/html");
Otherwise it is returned as a 404 to jQuery's ajax and then goes into the error and complete bits.
You may wish to try loading a different test file first, something simple that way you can test the js separately and ensure that when you hit the php script directly in your browser that there are no errors shown.
Also in the future make sure you have all these ajax calls on the same domain as your php scripts(like you do now), otherwise ajax won't work across domains without adding a "Access-Control-Allow-Origin", "*" header.
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 am building a jQuery Mobile and PhoneGap application.
Here is some of my code to query data from an external server:
function showDetail(stationID){
$('#itemDetail').load('http://www.mywebsite.com/detailPage.php?stationId='+stationID, function(){
});
It works perfectly on my local machine, WAMP server, however when I compile the script and run on an actual device, Android, it does not work. The same thing applies to this form:
$('#addStationForm').on('submit', function(e) {
$.post( 'http://www.mywebsite.com/add_parser.php', $(this).serialize(), function(response) {
alert( response );
});
// disable default action
e.preventDefault();
});
Also I have whitelisted my server, so that is not the problem.
Any help would be greatly appriciated, thanks.
Are you trying to get data from a server and load it into a dom element?
If so use the .ajax function to perform a http request to get the data from the sever.
Check the following doc with good examples
http://api.jquery.com/jQuery.ajax/
Also provide more info about the type of data you are going to request receive to help you further in the configuration of the ajax call parameters.
You can also use getJSON but depending on your data and needs.
EDIT
Post is a shorthand of the ajax function.
Make sure your PHP does have the correct content-type in the headers. That is very important
Like:
header("Content-Type:text/plain");
or
header("Content-Type:text/html");
depending what you need, want.
Also you can debug the HTTP response using firebug or any other tool out there, and let us know what you got.
Also try to use the verbose option of the function, give it a try. Make sure you specify correctly the dataType and the data parameters.
$.ajax({
type: "POST",
url: url,
data: data,
dataType: "html" // DATA TYPE is ALSO VERY IMPORTANT
})
.done(function() {
alert( "success" );
})
.fail(function( XMLHttpRequest, textStatus, errorThrown ) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
});
Also, when you said "when I compile the script and run on an actual device, Android, it does not work.", what errors you got? use the FAIL function of the http request to print the errors (like in the example above).
I've been trying to get result from this Ajax command but only to end up with a failure
$.ajax({
type: "get",
url: "http://[localhost]:80**/*****/getdata.jws",
data: 'method=s**&Table=empservice&Condition=%22ID_Service%22%3D'+$(this).val()+'',
success: processSuccess,
error: processError
});
function processSuccess(data, status, req) {
if (status == "success")
alert("SUCCESS");
}
function processError(data, status, req) {
alert("ERROR");
}
}
});
This is supposed to call a jws web-service and return the XML result, I've tested the URL in the browser and it returns the wanted result XML ( the URL being url concatenated to "?" and data = http://[localhost]:80/*/getdata.jws?method=s**&Table=empservice&Condition=%22ID_Service%22%3D2) I've tried also to make a variable to get $(this).val() into it before the call but nothing works help please
ps: after the call I get the alert popup containing the "ERROR" message
ps2: you probably know it but I'll say it anyway [localhost] = localhost because the website do not allow localhost in a link
Try changing your error handler to something like this so you get more info than just "ERROR". This will write the actual error to the Firebug console. Also, take a look at the Firebug console to see what is actually being sent. I am assuming you aware I am referring to Firefox with the Firebug add-on.
error : function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
TD
I found it, I need to use a proxy since AJAX calls are not allowed outside of one's domain
if your domain is localhost:80
a call from localhost:80 to localhost:8081 for example is not allowed
a call from localhost:80 to sdlksdlk.com is not allowed
only calls from localhost:80 to localhost:80 are allowed (in this example of course)
What the best way to report a syntax error when I'm loading a JSON feed with jQuery? I can establish the error reporting settings like this:
error: function(xhr){
alert('Request Status: ' + xhr.status + ' Status Text: ' + xhr.statusText + ' ' + xhr.responseText);
}
however this function doesn't fire when the URL I've called loads a valid page (albeit not one with a JSON object in it). Futhermore, I can't check the data that it does return because (according to Firebug at least) jQuery.getJSON breaks at the syntax error before it passes the object to the function that executes it.
The reason I'd like to report errors is because this is my way of checking whether the user has supplied a URL that will produce a valid JSON feed.
Here's a related answer that requires control over what the server will respond with.
Here's the syntax error that Firebug gives me
The syntax error Firebug gives me http://img.skitch.com/20090623-8c97g47jha4mn6adqqtjd41cwy.jpg
Any ideas? Thanks
You can bind a function to global ajaxerror events$(document).ajaxError(function(event, request, ajaxOptions, thrownError){
if ( 4==request.readyState) { // failed after data has received
alert(ajaxOptions['url'] + " did not return valid json data");
}
else {
alert("something else wnet wrong");
}
});
or use $.ajax() instead of $.getJSON()function foo() {
// $.getJSON("http://localhost/test.txt", function(data){});
$.ajax({
type: "GET",
url: "http://localhost/test.txt",
success: function (data, textStatus) {
alert("succuess");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("request failed: " + textStatus);
},
dataType: "json"
});
}
edit: But you might want to keep in mind that both ajax(dataType:"json") and getJSON() (which simply invokes .ajax(dataType:"json") boil down to data = window["eval"]("(" + data + ")") ...this might not be what you want if you don't know what (arbitrary) data your script requests. And this could explain why firebug is catching a syntax error when you feed it an html document instead of json data.
In that case better request dataType:"string" und run the data through a fully fledged json parser lib.
Thanks to all who answered. Because I was calling a JSON feed from an external domain, I wasn't able to just use jQuery's AJAX functionality and pull the feed as "text" instead of "json". jQuery only allows you to pull "json" and "script" from a remote source.
What I ended up doing instead was writing a PHP script to make the external call that lived on my own server. I use jQuery AJAX to call this, pass the requested source in the URL, and then grab that as "text." I then run my own check to ensure that it's properly formatted JSON, and then parse it with another library. jQuery doesn't have the ability to parse JSON at the moment; $.getJSON only works if you pass a URL to it.
Call the URL or the XHR request directly in your browser's address bar, do a view-source and paste the result into and IDE that understands JavaScript. You'll probably spot a misplaced quote or something.
At least you'll be able to remove chunks of it until you find the offending syntax if nothing else.
Adding to Diodeus' answer, paste your potentially offending JSON into here this tool: http://jsonformatter.curiousconcept.com/
If you have firebug, you might even be able to hack together a way to use the site a service programmatically, though that may be frowned upon.