Matt
Matt

Reputation: 1063

calling php code with ajax results in an error

I'm trying to call some php code using ajax:

$(document).ready(function() {
    $("#email_address").on("keypress", function() {
        request = $.ajax({
            url: '../verify_email.php',
            data: {email: $("#email_address").val(),
                   submitted: true},
            type: 'post'
        });

        request.done(function(response) {
            //fooling around to see if this works
            if(response) {
                alert("valid email");
            } else {
                alert("invalid email");
            }
        });

        request.error(function(response) {
            alert("an error occurred");
        });
    });
});

However, the request.error function runs. I'm not too sure why. Here is the php code:

<?php
    if(isset($_POST['submitted']) and isset($_POST['email'])) {
        if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            echo 'true';
        } else {
            echo 'false';
        }
    }
?>

Thanks in advance.

Upvotes: 0

Views: 39

Answers (2)

Maxi Schvindt
Maxi Schvindt

Reputation: 1462

If your url work fine, in php try to return json ;)

<?php
    $return = false;

    if(isset($_POST['submitted']) and isset($_POST['email'])) {
        if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
            $return = true;
        } else {
            $return = false;
        }
    }

header('Content-Type: application/json');
echo json_encode(array('result' => $return));
die;

?>

And in javascript try:

request.done(function(response) {
            //fooling around to see if this works
            if(response.result) {
                alert("valid email");
            } else {
                alert("invalid email");
            }
        });

Upvotes: 1

Matt
Matt

Reputation: 1063

ugh, noob mistake. i had set the php url to be relative to the .js file instead of to the web page. it was supposed to be:

    request = $.ajax({
        url: 'verify_email.php'

instead of

    request = $.ajax({
        url: '../verify_email.php',

i figured it out with the use of Chrome's web inspector . i learned two new things today: what the url has to be relative to and how to use Chrome's web inspector. thanks all for your help

Upvotes: 1

Related Questions