thomas
thomas

Reputation: 27

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 the php file which connects to database and get mysql data. It works when it is run separately, but when called using ajax it doesn't work. Can someone please help to correct 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>";
    }
}
?>

Upvotes: 2

Views: 52334

Answers (2)

Sohanur
Sohanur

Reputation: 21

you did mistake in your code:

 echo "<li>$row['name']</li>";

This should be:

 echo "<li>".$row['name']."</li>";

try that...

Upvotes: 1

ffflabs
ffflabs

Reputation: 17511

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();
});

Keep in mind that jQuery's ajax expects an object as parameter. Inside an object the syntax is

{ key : value }

You had type="POST" which is correct in declarative syntax, but incorrect when defining an object key.

Second, the data property of the aforementioned object should be an object too. So instead of action=showroom it should be

{action:"showroom"}

Upvotes: 5

Related Questions