Touchy Vivace Touchy Vivace - 5 months ago 10
SQL Question

jQuery.ParseJson didn't return a value from mysql database

I have a div that will store a value from DB that parse from JSON

<div id='nsnt' class="huge"> </div>


I have a getdata.php to getdata from mysqldb

getdata.php

<?php
$objConnect = mysql_connect("localhost","xxxxxx","xxxxx") or die(mysql_error());
$objDB = mysql_select_db("musicstore");
$strSQL = "SELECT count(song_id) as cnt FROM song ";
$objQuery = mysql_query($strSQL) or die (mysql_error());
$intNumField = mysql_num_fields($objQuery);
$resultArray = array();
while($obResult = mysql_fetch_array($objQuery))
{
$arrCol = array();
for($i=0;$i<$intNumField;$i++)
{
$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
}
array_push($resultArray,$arrCol);

}

mysql_close($objConnect);

echo json_encode($resultArray);

?>


I use var_dump on $resultArray it's return a data perfectly

On my index.php I have a jQuery function to return data from getdata.php and display on
<div id='nsnt' class="huge"> </div>
like this

<script>

function getDataFromDb()
{
$.ajax({
url: "~/getdata.php" ,
type: "POST",
data: ''

})
.success(function(result) {
var obj = jQuery.parseJSON(result);
if(obj != '')
{
//$("#myTable tbody tr:not(:first-child)").remove();
$("#nsnt").empty();
$.each(obj, function(key, val) {
var m = val["cnt"];
$('#nsnt').append( m );
});
}
}

setInterval(getDataFromDb, 1000); // 1000 = 1 second
</script>


It's doesn't return anything

Answer

I think Success should be one of ajax properties, otherwise use .done(), try this :

$.ajax({ 
            url: "~/getdata.php" ,
            type: "POST",
            data: '',
            success : function(result) { 
                var obj = jQuery.parseJSON(result);
                if(obj != '')
                {
                      //$("#myTable tbody tr:not(:first-child)").remove();
                      $("#nsnt").empty();
                      $.each(obj, function(key, val) {
                          var m = val["cnt"];
                          $('#nsnt').append( m );

                      });
                }
            }
        });

or

 $.ajax({ 
            url: "~/getdata.php" ,
            type: "POST",
            data: '' 
        }).done(function(result) { 
                var obj = jQuery.parseJSON(result);
                if(obj != '')
                {
                      //$("#myTable tbody tr:not(:first-child)").remove();
                      $("#nsnt").empty();
                      $.each(obj, function(key, val) {
                          var m = val["cnt"];
                          $('#nsnt').append( m );

                      });
                };
       });
Comments