2

I'm having troubles using ajax and php. What I'm trying to do is call an ajax function that grabs a value from an form's input, and checks if that email exists in a database. Here is my current javascript:

//Checks for Existing Email
function checkExisting_email() {
    $.ajax({
        type: 'POST',
        url: 'checkExist.php',
        data: input
    });

emailExists = checkExisting_email();

//If it exists
if (emailExists) {
    alert("This email already exists!");
}

Unfortunately, I can't get my alert to go off. In my PHP function, it checks whether the input is a username or an email (just for my purposes, and so you know), and then it looks for it in either column. If it finds it, it returns true, and if not, it returns false:

include ('func_lib.php');
connect();
check($_POST['input']);

function check($args)
{
    $checkemail = "/^[a-z0-9]+([_\\.-][a-z0-9]+)*@([a-z0-9]+([\.-][a-z0-9]+)*)+\\.[a-z]{2,}$/i";
    if (!preg_match($checkemail, $args)) {
        //logic for username argument
        $sql = "SELECT * FROM `users` WHERE `username`='" . $args . "'";
        $res = mysql_query($sql) or die(mysql_error());

        if (mysql_num_rows($res) > 0) {
            return true;
        } else {
            return false;
        }
    } else {
        //logic for email argument
        $sql = "SELECT * FROM `users` WHERE `email`='" . $args . "'";
        $res = mysql_query($sql) or die(mysql_error());

        if (mysql_num_rows($res) > 0) {
            return true;
        } else {
            return false;
        }
    }

}

SO my issue is, how does ajax respond to these returns, and how do I make ajax function accordingly? Mainly, why doesn't this work?

Any help is very much appreciated. Thank you!

Sawyer
  • 77
  • 1
  • 4
  • Off-topic: your PHP is vunerable to XSS attacks as you're passing the $_POST variables directly to your MySQL query without using some escaping function like `mysql_real_escape_string()`. – cmbuckley May 08 '11 at 20:49
  • Buckley, i think you mean sql injection as xss is a front end thing that relies on a user's ability to run arbitrary javascript. – BRampersad May 08 '11 at 21:12

2 Answers2

1

You need to add the success option to your Ajax request, which is the JS function which gets executed when the XHR succeeds. Have a look at the jQuery documentation for more info.

Without running the script, I think you'll find that $_POST['input'] is empty; you need to pass your data as something like data: {'input': input} to do that.

Your PHP also needs to return some content to the script; consider changing your call to check() to something like this:

echo (check($_POST) ? 'true' : 'false');

You can now check the content in JavaScript.

cmbuckley
  • 40,217
  • 9
  • 77
  • 91
  • Thanks for the response. So if I have success there, what would it look like? The data returned from the server would be what data? Basically, I just need that ajax call to return true or false, but I'm getting 'emailExists' as 'undefined'. – Sawyer May 08 '11 at 20:51
  • The Ajax call by default won't return anything, as it's asynchronous. You need to create a callback function like: `function callback(data, status, xhr) { if (data == 'true') { alert('Already exists!'); } }` and then add `success: callback` to your `.ajax` call. The documentation link above has a bit more info about asynchronous operations. – cmbuckley May 08 '11 at 20:59
  • I see what you mean, and I've actually tried that. My trouble is getting that data variable to return true. check($_POST['input']); function check($args).... That's where my trouble is, I'm not sure how php interacts with ajax, so how is my variable being fed over to the php, and then returned? Is it returning true, or trying to return a variable? So many questions.. Point is, I don't even think success is being called because it's unsuccessful! Thanks again for the response. ;) – Sawyer May 08 '11 at 21:06
  • See my edit I made to the answer above: you need to pass the POST variables correctly from the JavaScript, either with `data: 'input=me@example.com'` or `data: {input: 'me@example.com'}`. By default, the POST data is passed like a query string would be. You don't even need to use POST: you could use GET, and have your URL as `checkExist.php?input=me@example.com`. you would then pass `$_GET['input']` to `check()`. But I'd advise sticking with POST. – cmbuckley May 08 '11 at 22:43
  • As it turns out I'm an idiot! I tested with statuscode for a 404 error, and was led to find out I wasn't loading my file at all! I thought the ajax would load from the /js folder, but it loaded from the root, and the php was in /includes. Anyways, thank you a million times for the help and sticking through it with me! Very appreciated. – Sawyer May 09 '11 at 02:30
1

Basically ajax is a hand-shaking routine with your server.

Ajax:

$.post('yoursite.com/pagewithfunction.php',
    {postkey1:postvalue1, postkey2:postvalue2...},
    function (response) {
       // response is the data echo'd by your server
    }, 'json'
);

pagewithfunction:

yourFunction(){
   $var1 = $_POST['postkey1'];....
   $result = dosomething($var1..);
   echo json_encode($result); // this is passed into your function(response) of ajax call
}

So in $.post you have the url of the php page with the function, { var:val } is the post data, and function(response) is where you handle the data that is echo'd from your server -- the variable, response, is the content that is echo'd.

Atticus
  • 6,585
  • 10
  • 35
  • 57