help debugging an ajax problem - ajax

Anyone have any idea why this isn't working?
$(function(){
console.log('ready');
$.ajax({
dataType : 'jsonp',
jsonp : 'js',
url : 'http://monitor.302br.net/MonitorScoreServlet',
beforeSend : function(jqXHR, settings) {
console.info('in beforeSend');
console.log(jqXHR, settings);
},
error : function(jqXHR, textStatus, errorThrown) {
console.info('in error');
console.log(jqXHR, textStatus, errorThrown);
},
complete : function(jqXHR, textStatus) {
console.info('in complete');
console.log(jqXHR, textStatus);
},
success: function(data, textStatus, jqXHR){
console.info('in success');
console.log(data, textStatus, jqXHR);
}
});
});
This was working till recently. The beforeSend handler never fires, but you can see the ajax call being made in firebug, and if you go to the url, it seems to return acceptably formatted results (the same results as before):
http://monitor.302br.net/MonitorScoreServlet?js=jsonp1298046640938
text/javascript:
(84.3);
If I comment out the url, the beforeSend fires, but of course, there's no url....
Any ideas?

AJAX requests are, by definition, restricted to your current domain. Therefore, you cannot request an external URL from your domain.

Ok, I feel dumb. Here's what I think happened: the server used to be set up to take the js param as a callback function. So a url like:
http://monitor.302br.net/MonitorScoreServlet?js=foo
would result in:
foo(84.1);
Whenever we looked in the browser, we were just looking at:
http://monitor.302br.net/MonitorScoreServlet?js
which resulted in:
(84.1);
I assumed jQuery was doing some magic with that to turn it into usable data, but now I think that jQuery was creating something like:
function jsonp1298047240882(data) {
// do something with data
}
So when we changed our back-end code not to create the callback function call, the whole thing stopped working. (It's still weird that the beforeSend handler never gets called, though.)

Related

is there any difference between those AJAX methods?

I have two questions about jQuery AJAX.
1) Is there any difference between $.load() and $.ajax() used with type: 'GET'? They seem to do the same job.
2) This question is related to the code below. What happens, if I don't write the "type: GET" line at all? Does it mean the same thing?
$(document).ready(function() {
$('#update').click(function() {
$.ajax({
type: 'GET',
url: 'hello-ajax.html',
dataType: 'html',
success: function(html, textStatus) {
$('body').append(html);
},
error: function(xhr, textStatus, errorThrown) {
alert('An error occurred! ' + ( errorThrown ? errorThrown :
391
xhr.status );
}
});
});
});
Is it any different from
$(document).ready(function() {
$('#update').click(function() {
$.ajax({
url: 'hello-ajax.html',
dataType: 'html',
success: function(html, textStatus) {
$('body').append(html);
},
error: function(xhr, textStatus, errorThrown) {
alert('An error occurred! ' + ( errorThrown ? errorThrown :
391
xhr.status );
}
});
});
});
This is straight from jQuery Docs (http://api.jquery.com/load/)
The .load() method, unlike $.get(), allows us to specify a portion of
the remote document to be inserted. This is achieved with a special
syntax for the url parameter. If one or more space characters are
included in the string, the portion of the string following the first
space is assumed to be a jQuery selector that determines the content
to be loaded.
Since $.get() is simply the $.ajax() shorthand for "data: 'Get'", it would appear the only major difference is the ability to do the aforementioned (import partial sections of a document).
Edit: To answer your second question, GET is the default data type for the $.ajax() call, POST being your other option. You can read a bit about POST here (http://api.jquery.com/jQuery.post/)
Extracted from jQuery manual .load
This method is the simplest way to fetch data from the server. It is
roughly equivalent to $.get(url, data, success) except that it is a
method rather than global function and it has an implicit callback
function. When a successful response is detected (i.e. when textStatus
is "success" or "notmodified"), .load() sets the HTML contents of the
matched element to the returned data. This means that most uses of the
method can be quite simple:
$( "#result" ).load( "ajax/test.html" );
If no element is matched by the selector — in this case, if the
document does not contain an element with id="result" — the Ajax
request will not be sent.
I guess the difference is that .load() function allows to target the result into a DOM element. Like so
$( "#target" ).load( "source.html" );
And the ajax() method returns an object (eg. JSON) that can be the manipulated. etc. apart from more attributes.

how to specify a different function for each statement in JQuery .always() function

According to the official JQuery documentation:
jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown) { });
An alternative construct to the complete callback option, the
.always() method replaces the deprecated .complete()method.
In response to a successful request, the function's arguments are the
same as those of .done(): data, textStatus, and the jqXHR object. For
failed requests the arguments are the same as those of .fail(): the
jqXHR object, textStatus, and errorThrown. Refer to deferred.always()
for implementation details.
And let's say that I have the following ajax script :
$.ajax({
url: 'myPHPScript.php',
type: 'POST',
data: {
param_1: 'value_1',
param_n: 'value_n'…
},
username: 'myLogin',
password: 'myPassword',
beforeSend: function() {
alert('The object was created but not yet initilized');
}
}).done(function(data, textStatus, jqXHR) {
alert('All the request was sent and we received data');
}).fail(function(jqXHR, textStatus, errorThrown) {
alert('Error: the following error was occurred: ' + textStatus + ' Status : ' + jqXHR.Status);
}).always(function() {
// Here is my problem
});
In the .always() function, how can I specify a different function for each statement, I mean when the Deferred is resolved, the always() function gets passed the following params (data, textStatus, jqXHR) however if the deferred is rejected it gets passed (jqXHR, textStatus, errorThrown).
Thanks
The only good solution is not using the arguments in always - if you need code specific to the success/failure of the AJAX call out them in done or fail callbacks. Usually the always callback is a place where you do things such as re-enabling a button, hiding a throbber, etc. All those are things where you do not care about the result of the request.
Besides that, you could check arguments.length for the number of arguments and then access the arguments via arguments[0] etc. But relying on the argument count is a bad idea since it might not be future-proof.

Jquery: probleme with $.ajax (json datatype)

I have a problem to refresh a bloc in my page.
Here is the request:
> $("#pwd_lost_link").click(function(){
alert('1');
$.ajax({
type : 'POST',
url: 'test.php',
dataType: 'json',
data :{"nom" : "akbar"},
success : function(data){
$("#main_bloc").append(data.msg);
alert('2');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.responseText);
alert(errorThrown); }
}); })
and here is the php file
<?php
$return['nom'] = "ffrfrfrfr";
echo json_encode($return)
?>
It doesn't work. It give me a status error ( 0 ) and the page is automatically reloaded
Thanks
Michaël
Confusing question Michael, not sure what you mean by "the page is automatically reloaded" but you should do 2 things:
In the $.ajax() method, make sure your success called back is handling the data correctly. You are looking for data.msg but I don't see where .msg comes from.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
data: {},
dataType: "json",
url: url,
success: function(data) {
// parse data object so you can see what's being returned ex. alert(data) or alert(data[0]) or alert(data.nom)
},
error: function (xhr, status, error) {
// XHR DOM reference: http://www.w3schools.com/dom/dom_http.asp
// check for errors ex. alert(xhr.statusText);
}
});
On the PHP side, you may want to debug there to see what is being received and what you are sending back.
Aside from that using an XHR viewer like Firebug or Chrome's built-in utility (CTRL+SHIFT+I) can be very helpful.
And on a final note, if pwd_lost_link is a link elment a id="pwd_lost_link" href="..." then you will have to stop the browser from following the link before you process the AJAX.
$("#pwd_lost_link").click(function(e) {
e.preventDefault();
alert('1');
$.ajax({
...
});
If you aren't seeing the '1' being alerted then that is definitely your first problem.
You're trying to access data.msg, but your PHP script is only creating data.nom. So data.msg doesn't exist. Try changing data.msg to data.nom and see if this does what you want.

jQuery .ajax call shows success when computer disconnects. How to induce ajax error state?

I have the following bog standard jQuery ajax request. I've been trying to induce an error state by disconnecting my computer from the network mid-request (the server takes 10 seconds to reply so this is simple).
When I disconnect alert('Success: '+ json); is called, with null for the response json. I would expect the error part to be called.
Anyone know why the disconnect is being treated as a success, and how instead to induce a fail?
$.ajax({
url : 'post.php',
data : { id : 123 },
type: 'POST',
dataType : 'json',
success : function(json) {
alert('Success: '+ json);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error: ' + errorThrown);
},
complete : function(xhr, status) {
}
});
I think there was/is a bug since the release of jQuery 1.4.
After upgrading from 1.3.2 I noticed that calling an abort on the XMLHttpRequest object triggered the success callback, not the error callback. After poking around the codebase, I noticed that they had replaced the typical abort method with a custom one. Could have something to do with that.
Here's a post about it:
http://forum.jquery.com/topic/after-aborting-an-ajax-call-success-event-is-still-being-fired
$.ajax({
url : 'post.php',
data : { id : 123 },
type: 'POST',
dataType : 'json',
success : function(json) {
if(json!=null){
alert('Success');
}else{
exceptionAjax(0,"no server data");
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
exceptionAjax(XMLHttpRequest.statusText,XMLHttpRequest.responseText);
},
complete : function(xhr, status) {
}
});
function exceptionAjax(responseStatus,responseText){
alert('Error');
}

Check status of a jQuery ajax request

It seems that the success, error, and complete callbacks only fire when the ajax request is able to get some response from the server.
So if I shut down the server the following error callback is not executed and the request fails silently.
$.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function() {
alert("success");
},
error: function() {
alert("error");
}
});
What's the best way to throw an error when the server can't be reached at all.
Edit - From what I've tried and read it appears that jQuery's built in error handling doesn't work with JSONP, or dataType: "script". So I'm going to try setting a manual timeout.
Edit - Did a little more research and it looks like not only does the ajax error callback not work, but you can't abort an ajax request with dataType script or jsonp, and those requests ignore the timeout setting.
There is an alternative - the jquery-jsonp plugin, but it uses hidden iframes which I'd rather avoid. So I've settled on creating a manual timeout as suggested below. You can't abort the request if it times out, which means the script may still load even after the timeout, but at least something will fire if the server is unavailable.
You can use a setTimeout, and clear it with clearTimeout in the complete handler.
var reqTimeout = setTimeout(function()
{
alert("Request timed out.");
}, 5000);
var xhr = $.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function() {
alert("success");
},
error: function() {
alert("error");
},
complete: function() {
clearTimeout(reqTimeout);
}
});
jQuery.ajax already has a timeout preference and it should call your error handler should the request time out. Check out the fantastic documentation which says — I’d quote it here, emphasis mine:
timeoutNumber
Set a local timeout (in milliseconds) for the request…
and:
error (XMLHttpRequest, textStatus, errorThrown) Function
A function to be called if the request fails. The function is passed three arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror". This is an Ajax Event.
error: function (jqXHR, textStatus, errorthrown) {
if (jqXHR.readyState == 0) {
//Network error, i.e. server stopped, timeout, connection refused, CORS, etc.
}
else if (jqXHR.readyState == 4) {
//HTTP error, i.e. 404 Not found, Internal Server 500, etc.
}
}
Use readyState of XMLHttpRequest to determine the status of the ajax request.
'readyState' holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
If I remember correctly, jQuery throws exceptions. Thus, you should be able to work with a try { ... } catch() { ... } and handle it there.
You can use Jquery's AjaxSetup to handle your error handling.
$.ajax({
type: "GET",
url: "http://localhost:3000/",
dataType: "script",
success: function () {
alert("success");
}, error: function () {
alert("error");
}
//AJAX SETUP "error"//
$.ajaxSetup({
"error": function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + ' ' + textStatus + ' ' + errorThrown); //however you want
}
});
in ie8,can use:
success: function(data, textStatus, XMLHttpRequest) {
if("success"==textStatus&&XMLHttpRequest){
alert("success");
}else{
alert("server down");
}
}
but it's can't work on chrome,firefox...
i tried

Resources