Get data from mysql database using php and jquery ajax
I want to get data from mysql database using php and jquery ajax. "process.php" is a php file that connects to the database and receives the mysql data. It works when it's run separately, but when called using ajax, it doesn't work. Can someone please help fix the error? Here is my html file:
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function showRoom(){
$.ajax({
type:"POST",
url:"process.php",
data:{action:showroom},
success:function(data){
$("#content").html(data);
}
});
}
showRoom();
});
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
Here is my process.php file
<?php
$link=mysqli_connect("localhost","root","raspberry","homebot");
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_error();
$action=$_POST["action"];
if($action=="showroom"){
$query="SELECT * FROM user";
$show=mysqli_query($link,$query) or die ("Error");
while($row=mysqli_fetch_array($show)){
echo "<li>$row['name']</li>";
}
}
?>
+2
source to share
2 answers
There are two syntax errors in your ajax call:
$(document).ready(function(){
function showRoom(){
$.ajax({
type:"POST",
url:"process.php",
data:{action:"showroom"},
success:function(data){
$("#content").html(data);
}
});
}
showRoom();
});
Be aware that jQuery ajax expects an object as a parameter. Syntax inside an object
{ key : value }
You had type = "POST", which is correct in declarative syntax, but incorrect in defining the object key.
Second, the data property of the above object must also be an object. So instead of action = showroom it should be
{action:"showroom"}
+4
source to share