I am making an AJAX call to my PHP script, via $.getJSON. The problem is, PHP is returning json-encoded data, but my script is not console.logging anything at all.
function Club(){
this.URL = "http://localhost/imp03/includes/ajaxCall.php";
}
Club.prototype.loadData = function(){
$.getJSON(Club.URL, function(data){
console.log(data);
});
}
There are no errors in the console, and this is my PHP script.
$db = new Database(HOST, USER, PASS, DB);
$array = $db->getData();
header('Content-Type: application/json');
echo json_encode($array);
exit;
This is the method in my Database class, responsible for getting data
public function getData(){
try{
$sql = $this->db->prepare("SELECT * FROM inlever3");
$sql->execute();
$result = $sql->fetchAll();
return $result;
} catch(PDOException $e){
echo $e;
return false;
}
}
Club
is the function, which doesn't have the URL
property.
Club.prototype.loadData = function(){
$.getJSON(Club.URL, function(data){
console.log(data);
});
}
should be
Club.prototype.loadData = function(){
// here change Club.URL to this.URL
$.getJSON(this.URL, function(data){
console.log(data);
});
}
And use it like:
var club = new Club();
club.loadData();
Just tried it, it works as intended:
You need to use this.URL
not Club.URL
on the $.getJSON()
call
test.php
<?php
if (isset($_GET['loadData']))
{
// dummy data
exit(json_encode(
array('hello' => 'world')
));
}
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
function Club(){
this.URL = "test.php?loadData";
}
Club.prototype.loadData = function(){
$.getJSON(this.URL, function(data){
console.log(data);
});
}
var c = new Club();
c.loadData();
</script>
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.