I try to get the content of my mysql database to my website. For this i need Javascript to work with the data. The Problem is that I just want to use php to get the data out of the database. Thes rest, I want to do with an ajax request, but I don't get this. Here my try:
This is the database.php file
<?php
$pdo=new PDO("mysql:dbname=markers;host=127.0.0.1","root","");
$stmt = $pdo->query("SELECT * FROM markers");
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($results);
?>
And this is my try for the ajax request:
$(function(){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data['id'];
var vname = data['desc'];
}
});
});
The Problem, I don't get the content, I just got undefined returns.
And is this a good solution for a big database? On every pagevisit of a user, the mysql - statement gets execute and the whole db table gets encodes in json for the ajax request.
Thanks :)
2 Answers 2
It is just because you are getting a two dimensional array object ,, try something as below
$(function(){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
//var obj=JSON.parse(data);
var obj=data;
for (var x in obj)
{
alert(obj[x].id + " AND " + obj[x].desc);
}
}
});
});
Comments
The best way to know exact happening is get the object details from server response
.. You will find the errors while doing this
$(function(){
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
alert(JSON.parse(data));
}
});
});
{"id":"1","desc":"Frankie Johnnie & Luigo Too","address":"939 W El Camino Real, Mountain View, CA","lat":"37.386337","lng":"-122.085823"},