This is my ajax call:
var urlstring = '/search/';
$.ajax({
url: urlstring+'model.php',
type: 'GET',
dataType: 'text',
'data': 'test=1',
error: function(xhr, status, error) {
console.debug(error);
},
success: function() {
console.log('success');
},
complete: function(data) {
console.log('complete');
console.debug(data);
}
});
When I change dataType: 'json'
, I get this error:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data Stack trace: jQuery.parseJSON@ http://localhost/search/js/vendor/jquery.js:7964:9 ajaxConvert@ http://localhost/search/js/vendor/jquery.js:8246:19 done@ http://localhost/search/js/vendor/jquery.js:8707:15 .send/callback/<@ http://localhost/search/js/vendor/jquery.js:9123:9
I returned the data from php like this for json type:
json_encode($data);
I also tried setting the header before returning data:
header('Content-Type: application/json');
Now I tried changing dataType: 'text'
:
In php file,
<?php
include 'config.php';
class SearchModel extends Database
{
public $searchModel = null;
public function __construct()
{
$database = new Database();
}
public function fetchLocations()
{
$query = array();
$query[] = "SELECT * FROM `tbl_location`";
$query = implode(' ', $query);
$statement = self::$connection->prepare($query);
$statement->execute();
$data = $statement->fetchAll(PDO::FETCH_ASSOC);
return $data;
}
}
$searchModel = new SearchModel();
if (isset($_GET['test'])) {
$data = $searchModel->fetchLocations();
// header('Content-Type: application/json');
return $data;
}
?>
The data not received by my ajax call. I found that, success
was executing first before calling the php file. I set async:false, to no avail.
Then I added complete
below success
and this time I saw ajax was getting something else than the data I'm expecting from the server:
Object { readyState: 4, getResponseHeader: .ajax/jqXHR.getResponseHeader(), getAllResponseHeaders: .ajax/jqXHR.getAllResponseHeaders(), setRequestHeader: .ajax/jqXHR.setRequestHeader(), overrideMimeType: .ajax/jqXHR.overrideMimeType(), statusCode: .ajax/jqXHR.statusCode(), abort: .ajax/jqXHR.abort(), state: .Deferred/promise.state(), always: .Deferred/promise.always(), then: .Deferred/promise.then(), 11 more… }
replace
return $data;
with this
echo json_encode($data);
json_encode
will convert your array in json encoded string, then in JavaScript you can parse data using $.parseJSON(data)
.
we use echo
not return
when using ajax.
You need to echo json_encode($data);
in order to send data to the XHR request. Just return
will not work
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.