Reputation: 13
Im trying to read data from mysql database and pass it to my javascript file. I have search alot on internet and have found examples that doesnt work in my case.
.html file
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
<html xmlns='http://www.w3.org/1999/xhtml'>
<script language='JavaScript' type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
<title>Display Page</title>
</head>
<body>
<button type='button' id='getdata'>Get Data.</button>
<div id='result_table'>
</div>
<script type='text/javascript' language='javascript'>
$(document).ready(function(){
$('#getdata').click(function(){
alert("hello");
$.ajax({
url: 'db.php',
type:'POST',
dataType: 'json',
success: function(output_string){
alert(output_string);
},
error: function (xhr, ajaxOptions, thrownError){
alert(xhr.statusText);
alert(thrownError);
}
});
});
});
</script>
</body>
</html>
and .php file
<?php
echo 'hello';
$user = 'root';
$pass = '123';
$host = 'localhost';
$db = 'internetProgrammeringProj';
$connect = mysql_connect($host,$user,$pass);
$select = mysql_select_db($db,$connect);
$query = $_POST['query'];
$mysql_query = mysql_query("SELECT * FROM ratt ");
$temp = "";
$i = 0;
while($row = mysql_fletch_assoc($mysql_query)){
$temp = $row['id'];
$temp .= $row['namn'];
$temp .= $row['typ'];
$temp .= $row['url'];
$temp .= $row['forberedelse'];
$array[i] = $temp;
$i++;
}
echo json_encode($array);
?>
alert(xhr.statusText); gives parsererror
and
alert(thrownError); gives SyntaxError: JSON.parse: unexpected character
firebug doesnt display any error in console.
QUESTION: How do i get my program to get the content from the database and pass it with json to display it with alert in ajax?
Upvotes: 1
Views: 4830
Reputation: 28608
I just successfully ran this code.
All I had to do is remove the echo "hello"
at the beginning which messes up your JSON.
Some more tips you can use for future development:
alert('message')
. Use console.log('message')
. You can view the output of console.log
in "Developer's Area". In chrome you simply press F12. I think that in FF you need to install firebug or something. output_string
in function success
is actually an object. hello{ "key":"value"}
and immediately notice the nasty hello in the beginning. Read more about it at http://wiki.mograbi.info/developers-tools-for-web-developmentUpvotes: 1