Retrieve data from database in PHP and display them in JQuery on the same page
Today I need some help concerning one of my work. I'm trying to display, in JQuery, some data I retrieved, in PHP, from my database.
I need to display the data in JQuery for some reasons...
My PHP and my JQuery are on the same page, index.php, but my problem is that my ajax won't display my data and no error appears so I don't know exactly where is my mistake.
Here is my code:
<?php
require 'inc/db-connect.php';
$title = array();
try{
$sql = "SELECT * FROM events";
$req = $db->query($sql);
}catch(PDOException $e){
echo 'Erreur: '.$e->getMessage();
}
while($res = $req->fetch()){
array_push($title, $res['title']);
}
echo json_encode($title);
$req->closeCursor();
?>
<!DOCTYPE html>
<html lang="fr">
<?php include('inc/head.html'); ?>
<body>
<div id="stage">
/**
* ALL MY HTML GOES HERE
**/
</div>
<!-- END STAGE -->
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
data: "",
dataType: 'json',
success: function(data){
console.log(data);
},
error: function(){
console.log('Failed to load data');
}
});
});
</script>
</body>
</html>
So when I load my page, my JQuery does the "console.log('Failed to load data')" which means there is an error but I can't find it.
Somebody can help me please ?
Thnx, Antho
EDIT 1:
It seems there is no problem with my PHP request because the echo display the data I retrieve from the database. Apparently the error comes from my ajax request.
I've set the URL parameters on 'index.php' but doesn't work neither.
EDIT 2:
After some researches it seems impossible to make a PHP request and an ajax request on the same page. So I'll try something else...
Answer
Solution:
What you are currently doing is this:
you are creating an output that looks like this:
Now there are multiple problems.
To fix this you could put it in 2 different files.
getmyjson.php
index.php
or you could put it in one file and use conditions to split it up
Answer
Solution:
Set the header of the content to type of json... Here is an example of setting header type.
Any malformed JSON is rejected and a parse error is thrown.