I have a php file that receives data from mySQL table. The mySQL table ‘user_spec’ has only one field ‘options’ that it returns. Then I convert returned data into JSON, under is code doing that.
<?php
$username = "user";
$password = "********";
$hostname = "localhost";
$dbh = mysql_connect($hostname, $username, $password) or die("Unable to connect
to MySQL"); //print "Connected to MySQL<br>";
$selected = mysql_select_db("spec",$dbh) or die("Could not select first_test");
$query = "SELECT * FROM user_spec";
$result=mysql_query($query);
echo json_encode(mysql_fetch_assoc($result));
?>
then in an HTML file, I try to output data by this piece of code But it is not working. I will be very thankful for any help.
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
function Preload() {
$.getJSON("Dhttp://localhost/conn_mysql.php", function(json){
alert("JSON Data: " + json.user_spec);
});}
</script></head>
<body onLoad="Preload()">
</body>
</html>
I think instead of using the file adress: “D:xampp/htdocs/conn_mysql.php” you must use an url defined by xampp such as “http://localhost/mytest/conn_mysql.php”
Another thing you need to look out is the method. $.getJSON (http://api.jquery.com/jQuery.getJSON/), as its name says, works with the GET method. Maybe you should try $.post or $.ajax (http://api.jquery.com/jQuery.post/).
Oh! And to start your script, not all the browsers supports the <body onload=””>. Furthermore, it waits for the page to be loaded, not the DOM, what can give you problems with your scripts sometimes.
You should use $(‘document’).ready(function(), that waits for the DOM to be loaded.
This way:
I hope it can be useful! ^^