views:

56

answers:

1

I have a site where users can enter Area Codes into a text field, but not every Area Code is in our database. I'm trying to do a very simple AJAX request to validate that the Area Code they entered is in our database, but for some reason I'm having trouble with it. Here is the stripped down version of the code I was using originally. This gets triggered on the submission of the form:

function validate() {
var areaCodeString = trim($('#areaCodeTextInput').val());
$("#areaCodeError").remove();
// If something has been entered
if ( areaCodeString != "" ) {
    $.post("/ajax/test.php", { 
            areaCodes : areaCodeString
         },
        function(data){
            console.log("finished with AJAX. Data: '" + data + "'");

            // If there was an invalid area code
            if ( data != "" ) {
                console.log("Something was returned from the ajax call");
                $("<p id='areaCodeError' class='error'>" + data + " is not listed in our database. To keep things simple, we only use the main area codes of a region. If you are not sure what your main area codes are, please use the map below.</p>").insertAfter("#areaCodeTextInputContainer");
                return false;
            }

            // Everything is okay
            else {
                return true;
            }
        });
}
// Nothing has been entered
else {
    $("<p id='areaCodeError' class='error'>You must choose an area code to be listed under.</p>").insertAfter("#areaCodeTextInputContainer");
    return false;
}

}

If I enter nothing, the "nothing has been entered" section works correctly. However if I enter something, I get a strange thing in my firefox log. It's an error, but with no HTTP response code. It's simply the name of the AJAX processing page with a red X. However, if I look at the "response" section, there is no error in the response section. To minimize the problems, I made the PHP file simply this

<?php echo 'test'; ?>

And it's not even printing out test. I don't understand what's going on here, since it's not giving me any sort of error code that would seem to indicate it couldn't find the file.

As a result of this, there is no response from the file, and thus "data" returned from the AJAX request is empty. However, I changed the "return true" in that section of the code to "return false" so I could debug it more easily, and the form is STILL submitting. It seems that when the AJAX request fails, it's just quitting on the Javascript and submitting the form.

Test #2, I used the $.ajax method instead so I could have an error handling method. Now this is my code:

$.ajax({
type: "POST",
url: "/ajax/test.php",
success: function(msg){
    alert( "Data Saved: " + msg );
},
error: function(msg) {
    alert("Error: " + msg );
}
});

I've included the alerts so there isn't any confusion as to when things are occurring. And I'm getting the "Data Saved" response, which means it thinks the AJAX request finished successfuly. However the msg variable is empty. And even weirder, the AJAX request isn't erroring out, but rather continuing indefinitely and never doing anything.

I have AJAX events happening elsewhere on the site, so I don't think it's some sort of server problem. However I've gone through all my testing things I can think of and stripped out all the variables and it's STILL not working, so I need some help.

A: 

I think you may have a scope problem here. I'm assuming you intend the return false to refer back to the validate function which in turn prevents the form from submitting. When you create a callback function for your ajax script, keep two factors in mind:

  • Its being called asynchronously. The rest of your script isn't going to wait around for the callback to execute.
  • The anonymous callback function has a scope of its own, meaning any return statements are local to that particular function.

Consider the following stripped down code with added comments:

function validate() {
    if ( areaCodeString != "" ) {
        $.post("/ajax/test.php", { 
                areaCodes : areaCodeString
             },
            function(data){
                // If there was an invalid area code
                if ( data != "" ) {
                    // This return refers to the anonymous callback function
                    return false;
                }
                // Everything is okay
                else {
                    // This return refers to the anonymous callback function
                    return true;
                }
            });
    }
    // Nothing has been entered
    else {
        // This return refers to the 'validate' function
        return false;
    }
}
Greg W
That's a really good point. I changed it so that instead of returning, they set a variable to true or false which is then returned at the end (outside the anonymous function).Unfortunately, it didn't solve the issue. I'm still fairly certain the problem is with the AJAX call somehow or the data being returned from it, simply because of the "error" in Firebug.
Ryan Giglio