php - Unexpected end of JSON input - Uncaught SyntaxError -
everybody. have ajax call returns me error mentioned in title. believe line causes error: var obj = jquery.parsejson(data);
maybe wrongly constructed userdata
.
this 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 getinfo.php:
if($_server['request_method'] == 'post') { $email = prepareinput($_post['email']); $password = prepareinput($_post['password']); $stmt = $connection->conn->prepare('select firstname,lastname,... tb_users email = ? , password = ?'); $stmt->bind_param('ss',$email,$password); $stmt->execute(); $result = $stmt->get_result(); $obj = $result->fetch_assoc(); echo json_encode($obj); }
can tell me if i'm doing wrong?
update
function prepareinput($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; }
data passed php empty if $obj
contains values (i checked echoing them) must problem echo json_encode($obj);
statement.
solution
i found answer - link. encoding problem. if strings not utf-8 json_encode()
return empty string deal need convert these strings utf-8.
since mention: success function not receive data
it seems server response empty, because (a) credentials wrong or (b) there error in php , code never reaches echo
line.
add error handling / confirmation in php , make sure $obj has value before 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 debugging sql
to test sql:
as first line in condition (method == post) add
echo json_encode(array('resp'=>'test')); exit;
, run ajax code.console.log()
should display {resp:test} json object. way know ajax call reaches part sql. if still not output else wrong in code...first use hardcoded sql: enter email/password in know give result. not use
->bind_param()
or$_post
data, execute plain sql statement , see if ajax returns value.if ajax works now, modify hardcoded sql move static email/password string
bind_param()
. still not using$_post
data now, check if bind_param method works. again check if ajax still working.if still working, use direkt $_post data in bind_param() call,
->bind_param('ss', $_post['email'], $_post['password'])
- if working, then know there's problem prepareinput() function.
when testing each step, should find out, part not working.
Comments
Post a Comment