4

everybody. I have an AJAX call which returns me an error mentioned in the title. I believe this is the line which causes error: var obj = jQuery.parseJSON(data); Maybe I wrongly constructed userData.

This is my jQuery:

var userData = 'email=' + email + '&password=' + password; 

$.ajax({
    type: 'POST',
    url: './api/getInfo.php',
    data: userData,
    success: function(data){
        var obj = jQuery.parseJSON(data); 

        $('#name').html(obj.firstName + ' ' + obj.lastName);
        ...
    },
    error: function(){
        alert('ERROR');
    }
});

And this is getInfo.php:

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
     $email = prepareInput($_POST['email']);
     $password = prepareInput($_POST['password']);

     $stmt = $connection->conn->prepare('SELECT firstName,lastName,... FROM tb_users WHERE email = ? AND password = ?');
     $stmt->bind_param('ss',$email,$password);

     $stmt->execute();

     $result = $stmt->get_result();

     $obj = $result->fetch_assoc();

     echo json_encode($obj);
}

Can someone tell me if I'm doing something wrong?

UPDATE

function prepareInput($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);

    return $data;
}

Data passed from PHP is empty even if $obj contains values (I checked this by echoing them) so it must be the problem with echo json_encode($obj); statement.

SOLUTION

I finally found the answer - Link. It was encoding problem. If some strings are not UTF-8 json_encode() will return empty string so to deal with this you need to convert these strings to UTF-8.

Community
  • 1
  • 1
NutCracker
  • 11,485
  • 4
  • 44
  • 68

2 Answers2

3

Since you mention: the success function does not receive any data

It seems the server response is empty, because (a) the credentials are wrong or (b) there is an error in PHP and your code never reaches the echo line.

Add some error handling / confirmation in PHP and make sure that $obj has a value before you return it.

try {
  // ... sql code

  if ( $obj && is_array( $obj ) ) {
    echo json_encode( $obj );
  } else {
    echo json_encode( array( 'error' => 'wrong username or password' ) );
  }
} catch (Exception $ex) {
  echo json_encode( array( 'error' => $ex->getMessage() ) );
}

Update; notes for debugging the SQL

To test the SQL:

  1. As first line in the condition (method == POST) add echo json_encode(array('resp'=>'test')); exit; and run the Ajax code. Your console.log() should now display the {resp:test} JSON object. This way you know that your ajax call actually reaches the part with the SQL. If you still do not get any output then something else is wrong in your code...

  2. First use a hardcoded SQL: Just enter email/password in WHERE that you know will give you a result. Do not use ->bind_param() or $_POST data, just execute a plain SQL statement and see if AJAX returns a value.

  3. If Ajax works now, then modify the hardcoded SQL to move the static email/password string into bind_param(). Still not using $_POST data now, but we check if the bind_param method works. Again check if Ajax is still working.

  4. If still working, then use direkt $_POST data in the bind_param() call, like ->bind_param('ss', $_POST['email'], $_POST['password']) - if this is working, then you know that there's a problem with the prepareInput() function.

When testing each step, you should quickly find out, which part is not working.

Philipp
  • 10,240
  • 8
  • 59
  • 71
  • I have tested each of these four steps and everything is working fine. Array `$obj` has values (I checked this by echoing its values) but somehow `echo json_encode($obj);` returns nothing to AJAX. – NutCracker Aug 30 '16 at 07:37
0

You don't seem to check if your execute is a success before you use the result.

If I was you I will try to console.log(data) before use jsonParse. I think you will find some surprise.

Also, check your apache logs. Maybe PHP throw you some warnings in it.

avallete
  • 53
  • 8
  • I already tried `console.log(data)` but nothing is written to console. Also there are no errors or warning in Apache logs. – NutCracker Aug 29 '16 at 10:54
  • I suspect the SQL is wrong; maybe your `prepareInput()` modifies the password or email address and the SQL returns no result. – Philipp Aug 29 '16 at 10:56