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.

8
  • 1
    add a console.log(data) as first line in the success handler to check the server response. I bet there is some extra code at the end/before your JSON string that causes the error...
    – Philipp
    Commented Aug 29, 2016 at 10:20
  • 1
    try adding dataType:"json" in your ajax call Commented Aug 29, 2016 at 10:20
  • 1
    You should use an object as ajax data instead of building a string by your own. Like this: data: { email: email, password: password }.
    – eisbehr
    Commented Aug 29, 2016 at 10:21
  • @Philipp I tried this but there is no response. @Mir If I add dataType: 'json' error occurs.
    – NutCracker
    Commented Aug 29, 2016 at 10:23
  • @eisbehr If change this, error is still there.
    – NutCracker
    Commented Aug 29, 2016 at 10:25

3 Answers 3

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.

1
  • 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
    Commented Aug 30, 2016 at 7: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.

2
  • I already tried console.log(data) but nothing is written to console. Also there are no errors or warning in Apache logs.
    – NutCracker
    Commented Aug 29, 2016 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
    Commented Aug 29, 2016 at 10:56
0

I had such a problem, struggled with it for a couple of days. It turned out that the problem was in the database encoding, which I changed using this command in the database:

ALTER DATABASE your_database_name CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

And I also needed to set the connection encoding when connecting to the MySQL database via PHP using the mysqli_set_charset() function in the php file.

After that everything worked.

Not the answer you're looking for? Browse other questions tagged or ask your own question.