user1504308
user1504308

Reputation: 25

Ajax variable value to javascript

I've been on a problem for hours without finding any issue...

I have a registration form for users to create accounts. When the submit button is pressed a validateForm function is called.

In this function I do some javascript tests that work, but then I need to verify that the username is available. For this I created an external PHP file and call it using $.ajax.

Here is part of the code :

function validateRegistration(){
// Some tests....

// Check if username is already used
// Call external php file to get information about the username
$.ajax({
    url: 'AjaxFunctions/getUsernameAjax.php',
    data: "username=" + $("#username").val(),
    success: function(data){
        // Username already in use
        if(data == "ko"){
            // Stop validateForm()
        }
        // Username not used yet
        else{
            // Continue tests
        }
    }
});
// Other tests
}

My question is how can I make validateForm() return false from inside the $.ajax ? Could I for instance declare a js variable before the Ajax part and set it with Ajax ?

I guess the answer is obvious but I'm absolutely new to Ajax and I can't get it...

Thanks a lot for your help!

Upvotes: 2

Views: 1552

Answers (5)

apsillers
apsillers

Reputation: 116040

The traditional solution here is to pass a callback function to validateRegistration which expects a boolean value. Have the Ajax function call the callback function when it completes.

The onsubmit handler expects a return value immeidately, so performing an asynchronous test within your submit event handler is a fairly unituitive way to do things. You should instead perform the test as soon as possible (e.g. as soon as the user enters a username) and then store the result of username validation in a global variable, which is later checked at submit time.

// global variable indicating that all is clear for submission
shouldSubmit = false;

// run this when the user enters an name, e.g. onkeyup or onchange on the username field
function validateRegistration(callback) {
    shouldSubmit = false;
    // number of ajax calls should be minimized
    // so do all other checks first
    if(username.length < 3) {
        callback(false);
    } else if(username.indexOf("spam") != -1) {
        callback(false)
    } else {
        $.ajax({
            ....
            success: function() {
                if(data == "ko") {
                    callback(false);
                } else {
                    callback(true);
                }
            }
        });
    }
}

Now call validateRegistration with a function argument:

validateRegistration(function(result) {
    alert("username valid? " + result);
    if(result) {
        $("#username").addClass("valid-checkmark");
    } else {
        $("#username").addClass("invalid-xmark");
    }
    shouldSubmit = result;
});

Now use the global variable shouldSubmit in your form's submit event handler to optionally block form submission.

Upvotes: 0

Rob Forrest
Rob Forrest

Reputation: 7450

If the goal is to check a username availability, how about checking it as or just after the username is typed in. For example you could either bind it to the keyUp event for keystrokes or the blur event for when you leave the text box.

This would mean that by the time the user gets to the submit button, that part of the form would already be validated.

Upvotes: 0

I like php
I like php

Reputation: 29

In the php, if you print out JSON like:

echo json_encode(array("ko"=>"good"));

shows up as:

{
 "ko":"good"
}

then in the function it would be

if(data.ko == "good"){
  //do stuff
}

This is how I normally do it. You can get the variable by using the name you used in the JSON so you can have other things if you need.

Upvotes: 0

Vidar S. Ramdal
Vidar S. Ramdal

Reputation: 1242

You could make a synchronous ajax call, instead of an asynchronous, as you're doing now. This means that the Ajax call will complete before the next lines of code are executed.

To do so in jQuery, just add async: false to your request object:

var someVariable;
$.ajax({
    url: 'AjaxFunctions/getUsernameAjax.php',
    data: "username=" + $("#username").val(),
    success: function(data){
        // Username already in use
        someVariable = "something";
        if(data == "ko"){
            // Stop validateForm()
        }
        // Username not used yet
        else{
            // Continue tests
        }
    },
    async: false
});
alert(someVariable); // should alert 'something', as long as the ajax request was successful

Upvotes: 0

David Mulder
David Mulder

Reputation: 27030

To achieve this you can either do a synchronous ajax call like described in this answer, but that's something which is incredibly dangerous for the performance of your website.

Alternatively - and this is the right way - you should have an external variable whether the username is available, as soon as the user inputs something you do the request and if it's valid you change the variable otherwise you show an warning message. Next in your validateRegistration() function you only check the external variable (+ possible some form of callback, depending on where you call it from). The advantage being that the user can still continue doing things (like filling out the rest of the form) whilst the request is pending.

Upvotes: 1

Related Questions