DigitalJedi805
DigitalJedi805

Reputation: 1460

Why is the AJAX call coming back with a status code 0

I'm exploring AJAX form submission and I've run into a problem where my AJAX call is returning an error with little to no information as to why.

My SubmitForm method is as follows:

function SubmitForm(FormId,Container) 
{  
    var FormElement = document.getElementById(FormId);
    var TargetUrl = document.URL + "resource/form/" + FormId + ".php";
    var SubmitUrl = TargetUrl + "?action=submit";
    var SuccessUrl = TargetUrl + "?action=success";
    var ErrorUrl = TargetUrl + "?action=failure";
    var DataString = "";

    for( var i = 0; i < FormElement.length; i++ )
    {
        if( i > 0 )
            DataString += "&"

        DataString += FormElement.elements[i].name + "=" + FormElement[i].value;
    } 

    $.ajax({  
      type: "POST",  
      url: SubmitUrl,  
      data: DataString,  
      success: function() { 
        RequestAjax(Container,SuccessUrl); 
      },
      error: function(object, textStatus, errorThrown){
      console.log(textStatus + "|" + errorThrown + "|" + object.status + "|" + object.responseText);
          RequestAjax(Container,ErrorUrl);
      }
    });
    return false; 
}

Being submit from:

<input name="submit" type="submit" id="submit" class="submit" value="Login" onClick="javascript: SubmitForm('loginForm','userData');" />

And I am getting output something like this;

error||0| 

I know that the URL that I'm trying to hit exists, and have used basically identical code in another instance to submit a form, but am encountering the truly indescript problem that you see above.

Any advice would be much appreciated.

Upvotes: 0

Views: 138

Answers (3)

Alexandre Danault
Alexandre Danault

Reputation: 8672

First thing I'd try would be to UrlEncode your values:

var DataString = "";

for( var i = 0; i < FormElement.length; i++ )
{
    if( i > 0 )
        DataString += "&"

    DataString += FormElement.elements[i].name + "=" + encodeURI(FormElement[i].value);
} 

Upvotes: 1

Tim
Tim

Reputation: 8606

I find this happens when an Ajax process is aborted. This can happen if the page is unloaded, or if the server connection is reset for some reason.

btw: if you're using jQuery you're better off building your postdata string with $(FormElement).serialize()

Upvotes: 0

epascarello
epascarello

Reputation: 207501

Status of zero comes from when the page is running off the file protocol or the page is refreshed when the Ajax call is made. Without seeing how your method is being called, I am assuming you are doing it like

<form onsubmit="SubmitForm();" />

You are missing the return

<form onsubmit="return SubmitForm();" />
                ^^^^^^

or with the input's click

<input type="submit" onclick="SubmitForm();" />

which should be

<input type="submit" onclick="return SubmitForm();" />
                              ^^^^^^

Upvotes: 1

Related Questions