-1

I have the following script in my javascript...

$.ajax({
    type: 'POST',
    url: 'http://www.example.com/ajax',
    data: {email: val},
    success: function(response) {   
             alert(response);
    }
});

And my php file looks like this...

    if ($_REQUEST['email']) {

$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {

    echo json_encode(error = false);
}
else {

    echo json_encode(error = true);
}

    }

I cannot get either the variable error of true or false out of the ajax call?

Does it matter how I put the data into the ajax call?

At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.

3
  • Are you using firebug or a similar tool to view the AJAX request/response? Commented Sep 24, 2011 at 2:12
  • I have firebug lite for chrome. The ajax request was sucessfull but was returning [object]:[object] before. Commented Sep 24, 2011 at 2:17
  • 1
    Good deal. Thanks for the update. FYI the chrome developer tools are pretty darn good themselves if you want to try to ween yourself off of firebug lite. Commented Sep 24, 2011 at 2:25

2 Answers 2

2

Try this instead. Your current code should give you a syntax error.

if (!$q -> rowCount()) {

    echo json_encode(array('error' => false));
}
else {

    echo json_encode(array( 'error' => true ))
}
Sign up to request clarification or add additional context in comments.

3 Comments

This works but why does it have to be in an array? Thanks Interstellar
Because json_encode() takes a mixed argument as its parameter, but more than that an array is the most logical structure to store a key, value pair in. The array eventually gets translated into {"error":true}
This works but how do I call the variable now? error isn't it, and I tried response['error'], response[error], response["error"]? This JSON stuff is annoying lol.
1

In your code, the return parameter is json

$.ajax({
    type: 'POST',
    url: 'http://www.example.com/ajax',
    dataType: 'json',
    data: {email: val},
    success: function(response) {   
             alert(response);
    }
});

PHP FILES

if ($_REQUEST['email']) {

   $q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
   $q -> execute(array($_REQUEST['email']));
   if (!$q -> rowCount()) {
       echo json_encode(error = false);
       return json_encode(error = false);
   } else {

       echo json_encode(error = true);
       return json_encode(error = true);
    }
 }

1 Comment

Yes, you are right, I thought the problem was without dataType.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.