Aoi M. Serizawa Aoi M. Serizawa - 2 months ago 6
Ajax Question

Getting all the content of table and append it using ajax with jquery

I made a simple sample on how to insert using AJAX and retrieving it then append it in a

<div>
after getting it. But I am having trouble on getting all the content of the table, it's returning a null values.

<div id="wrap-body">
<form action method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>


jQuery:

<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();

$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:'username='+username+'&msg='+msg,
success: function (data){
$('#info').append("<p> you are:"+data.username+"</p> <p> your message is:"+data.mesg);
}
});
});
});
</script>


PHP:

<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';

$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);

$username = $_POST['username'];
$msg = $_POST['msg'];

$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";

if(@!mysql_query($insert)){
die('error insertion'.mysql_error());
}

$get = "SELECT * FROM info ";

$result=mysql_query($get)or die(mysql_error());

while ($row = mysql_fetch_array($result))
{
$return = $row['user_name'];
$return = $row['message'];
}
echo json_encode($return);
?>

GBD GBD
Answer

Your while should create array and then do json_encode

Try below code

$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
   'username'=>$row['user_name'],
   'mesg'=>$row['message']
);
}

echo json_encode($data);
exit

Now write your javascript success handler as below

$.ajax({
                type: 'POST',
                url: 'get.php',
                dataType: 'json',
                data:'username='+username+'&msg='+msg,
                success: function (data){
                   $.each(data, function(i, item) {
                     $('#info').append("<p> you are:"+data[i].username+"</p> <p> your message  is:"+data[i].mesg);
                   });‚Äč

                }
            });
Comments