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.