Kevin_TA
Kevin_TA

Reputation: 4685

Getting Return Value from AJAX

I have a PHP script that checks an email address to determine if it is valid or not. The function simply returns true or false. I am trying to implement an ajax call to the php file and return the true or false back to the javascript function. Currently I am getting nothing.

function validateForm() {
    var email = document.forms["contact"]["email"].value;
    var validEmail;

    $.ajax({
        type: "POST",
        url: "validateEmail.php",
        data: "email=" + email,
        success: function(result) {
            validEmail = result;
            console.log('result: ' + validEmail);
        }
    });
}

If I can retrieve the true or false I will then do some boolean checking to determine how to proceed. The function validateForm() is being called when the user clicks a form Submit button.

<form name="contact" action="submitOrder.php" onsubmit="return validateForm();" method="post">

I'd like the validateForm() function to return false if the email address is not valid so that submitOrder.php is never called but due to the asynchronous nature of AJAX, I am not sure how to do this.

UPDATE

The request is working correctly (I'm pretty sure). This is what I am seeing in Firebug. enter image description here I'm still not seeing anything returned. The console prints "result: ". I also changed validateEmail.php to return the number 17 and I still get nothing returned.

Thanks for any help!

Upvotes: 2

Views: 1151

Answers (7)

danasilver
danasilver

Reputation: 556

Using async: false is a poor way to use AJAX as you block up your javascript unnecessarily. Using a client side validator such as jQuery Validate is dangerous, as an attacker can disable javascript and submit an invalid form. Server side validation is a must and it can be done with good old AJAX!

The key is a callback. Anything you try to return from validateForm will be returned before your AJAX call returns because AJAX is asynchronous (non-blocking). This means you can't return the value from your AJAX success function without pausing all javascript execution. Instead, you pass in a callback function as a parameter that your AJAX success function can call. Inside that callback, you can do your boolean checking to figure out how to proceed. You can also do this directly inside the success function (which is actually a callback!) but the callback parameter and other function decouples the code a little bit, which is good practice. I modified your code to give you an example of what I mean.

function validateForm(callback) {
    var email = document.forms["contact"]["email"].value;
    var validEmail;

    $.ajax({
        type: "POST",
        url: "validateEmail.php",
        data: "email=" + email,
        success: function(result) {
            validEmail = result;
            console.log('result: ' + validEmail);
            callback(result);
        }
    });
}

function doSomethingWithResult(result) {
    if (result === True) {
        // Do true stuff
    } else {
        // Do false stuff
    }
}

validateForm(doSomethingWithResult);

Upvotes: 0

Josh Mein
Josh Mein

Reputation: 28665

It is not recommended to use the synchronous option for ajax calls because it can temporarily lock the browser. Notice the following quote from jquery's ajax() page.

Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.

Instead you can have the button that submits the form call the validateForm function and when the ajax success is called it can submit the form.

function validateForm() {
    var email = document.forms["contact"]["email"].value;

    $.ajax({
        type: "POST",
        url: "validateEmail.php",
        data: "email=" + email,
        success: function(result) {
            if (result == true)
                document.forms["contact"].submit();
        }
    });
}

Upvotes: 0

JMC
JMC

Reputation: 930

Use JQuery Validate plugin. Would be a lot simpler then hashing this out from scratch.

Upvotes: 1

jbnunn
jbnunn

Reputation: 6355

I think you'll need an event.preventDefault(); to get the async call to work correctly

$('#submit-button-id').click(function(event){ event.preventDefault(); });

This should stop the browser from submitting the form before any sort of validation is done. (Note, you'll want to give your submit button a class or ID that you can reference in order for this to fire).

http://api.jquery.com/event.preventDefault/

Upvotes: 0

Jeff Watkins
Jeff Watkins

Reputation: 6357

You could make the Ajax call submit if the result is valid if you don't want to make the AJAX call synchronous. Call your validateForm and return false to the onsubmit. (I wouldn't make validateForm itself return false as that would not be orthogonal).

Upvotes: 0

jx12345
jx12345

Reputation: 1670

I think you have a missing ; at the end of your jquery call

$.ajax({
    type: "POST",
    url: "validateEmail.php",
    data: "email=" + email,
    success: function(result) {
        validEmail = result;
        console.log('result: ' + validEmail);
    }
});

I'd recommend installing firebug so you can see what's going on with the ajax calls & responses - you should be able to debug it a lot easier then.

Upvotes: 0

Matt Dodge
Matt Dodge

Reputation: 11152

jQuery's ajax function is by default asynchronous. Meaning it makes the ajax request and then returns. You probably need to set the async parameter to false and then set validEmail in your success function like you are doing. Then you can safely return validEmail after the ajax call.

function validateForm() {
  var email = document.forms["contact"]["email"].value;
  var validEmail = false;

  $.ajax({
    type: "POST",
    url: "validateEmail.php",
    async: false,
    data: "email=" + email,
    success: function(result) {
        validEmail = result;
        console.log('result: ' + validEmail);
    }
  });

  return validEmail;
}

Upvotes: 0

Related Questions