Reputation: 3
I'm getting some data using php json, well the result bring me the html code too, so the page is giving me a unexpected token. Here my code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).on("ready", function(){
loadData();
});
var loadData = function(){
$.ajax({
type:"POST",
url:"Users.php"
}).done(function(data){
console.log(data);
var users = JSON.parse(data);
for(var i in users){
$("#content").append(users[i].nombre + " " + users[i].apellido + "<br>");
}
});
}
</script>
and this is what I see in the console
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
[{"nombre":"Joelbis","apellido":"Rosas"},{"nombre":"William","apellido":"Mazo"},{"nombre":"Mariana","apellido":"De Barros"},{"nombre":"Daniela","apellido":"Ramirez"}]
</body>
</html>
VM396:1 Uncaught SyntaxError: Unexpected token <(anonymous function) @ userview.php:22l @ jquery.min.js:4c.fireWith @ jquery.min.js:4k @ jquery.min.js:6(anonymous function) @ jquery.min.js:6
How I avoid the html code in the result?
Thank you.
Upvotes: 0
Views: 140
Reputation: 91
var loadData = function(){
$.ajax({
type:"POST",
url:"Users.php"
}).done(function(data){
console.log(data);
data = $(data).find('body').html();
var users = JSON.parse(data);
for(var i in users){
$("#content").append(users[i].nombre + " " + users[i].apellido + "<br>");
}
});
}
Try to parse data from html
Upvotes: 0
Reputation: 406
You need a php file that ONLY prints out the data you need returned. Like this:
Ajax Call
var loadData = function(){
$.ajax({
type:"POST",
url:"UserData.php"
}).done(function(data){
console.log(data);
var users = JSON.parse(data);
for(var i in users){
$("#content").append(users[i].nombre + " " + users[i].apellido + "<br>");
}
});
}
UserData.php
<?php
$sql = "SELECT nombre, apellido FROM pruebaUsuarios"; $result = mysqli_query($conexion, $sql);
$array_user = array(); while($data = mysqli_fetch_assoc($result)){ $array_user[] = $data; }
echo json_encode($array_user)
?>
Upvotes: 1
Reputation: 1342
Your backend script must stop right after echo json_encode($data)
, using die()
or exit()
which are the same. Otherwise it will feed the rest of your page to your AJAX frontend, which is what's currently happening.
Upvotes: 0