tags:

views:

70

answers:

2

doesn't work.. can't find any solution to prevent submit page reload only if ajax status is 200...

$('form.insarticolo').submit(function (e){  
     function getUrlStatus(url, callback) {
    $.ajax({
        type: "POST",
        url : url,
        data: ({ testo : $('[name=testo]').val() }),
        dataType: "XML",
            success : function(xml) { $('label').find('span').hide();}
        complete: function(xhr) { callback(xhr.status); }
    });
}

getUrlStatus('http://www.website', function(status) {
    if (status == 200)  { 
                    e.preventDefault();
            }
});
}); 
A: 

Try

$('form.insarticolo').submit(function (e){  
  if (!getUrlStatus('http://www.website'))
    $.ajax({
        type: "POST",
        url : url,
        data: ({ testo : $('[name=testo]').val() }),
        dataType: "XML",
            success : function(xml) { $('label').find('span').hide();}
        complete: function(xhr) { callback(xhr.status); }
    });
});

function getUrlStatus(url)
{
  var http = new XMLHttpRequest();
  http.open('HEAD', url, false);
  http.send();
  return http.status!=404;
}
JapanPro
+2  A: 

The .submit() function can be canceled by returning false in the passed function. See http://api.jquery.com/submit/. An issue you may have is that the .ajax() function is asynchronous by default so it will return and processing will continue. To do what you are trying to do you will need to set the ajax mode to synchronous (async : false) so that you can wait for the response. Then you can check the status code to see if it is 200. If it is return false otherwise return true. I haven't tested this code but something like this

$('form.insarticolo').submit(function (e){ 
    var retStatus; 
    $.ajax({
        type: "POST",
        url : url,
        async : false,
        data: ({ testo : $('[name=testo]').val() }),
        dataType: "XML",
        complete: function(xhr) { retStatus = xhr.status; });

    if(retStaus == 200)
        return false;
    else
        return true;
});

NOTE: Synchronous requests with jQuery 1.4.2 cause memory issues in IE unless you cleanup the request in the callback function. After processing the xhr you should do the following:

xhr.onreadystatechange = null; xhr.abort = null; xhr = null;

This is documented at http://dev.jquery.com/ticket/6242

K-Sid
@Kevin - +1. Thanks did not know about memory leak
Gutzofter
+1: good and absolutly correct answer and good information about http://dev.jquery.com/ticket/6242. I hope only that all scenaios can be realized with asynchrone requests, but the question has not enough information to get a better answer.
Oleg
thanks a lot, that works like a charm!!!!
federico