How to work with RETURN value (from server script) in AJAX

I'm trying to validate an email on server side using PHP. I'm doing this using jQuery "$.post()" function. I know I can do it with '$.ajax()' too.

But the problem is if server side PHP script RETURN a value then the jquery post or ajax both failed to catch the result, but if PHP 'echo' the result then it works perfectly.

My question is how do I can catch the result that was 'RETURN'ed by the PHP not 'ECHO'ed.

Currently my my JS code look like this:

function validate_email(email) {

    $.post('106_1.email.php', {email: email}, function (responseData) {

        $('#feedback').html(responseData);
    });
}

and PHP code looks like this:

$email = $_POST['email'] ?? null;

if ($email) {

    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {

        echo '<span class="text-primary">Email is valid.</span>';
    } else {

        echo '<span class="text-danger">Invalid Email ...!</span>';
    }
}

But I really wanted the PHP to return Boolean like following:

$email = $_POST['email'] ?? null;

if ($email) {

    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {

        return true;
    } else {

        return false;
    }
}

But if I do this or return anything other than Boolean, the jQuery code cannot catch that too.

But I need the PHP to 'return' result instead 'echo'

Any help will be highly appreciated.

Answers 1

  • Try this:

    Php:

    $email = $_POST['email'] ?? null;
    
    if ($email) {
    
        if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
            echo true;
        } else {
    
            echo false;
        }
    }
    

    Jquery:

    $.ajax({
        url : '106_1.email.php',
        data: {
            email: email
        },
        success: function(response){
            if(response)    // here response = true;
            {
                // do something
            }
            else
            {
                // do something
            }
        }
    });
    

Related Articles