启用AJAX的网络表单

I am new to Jquery and want some help from you guys.

i want to decode json data in jquery as i am able to pass data from php to ajax but after it came back in jquery it is not parsing it says undefined. the code is bellow

JavaSript file

$.post("GetData.php", function(data) {
        if(data==false)
            var tpl = '<p>no record found<p>'
        else
            var tpl = DrawTableRowsforSection(data);
            $("#result").append($(tpl));
},"json");


function DrawTableRowsforSection(p)
{
    alert(p.id[0]);
    var o = '<table>';
    for (var i = 0; i < p.length; i++)
        alert(p.id[i]);
        o += '<tr><td>'+p.id[i]+'</td><td>'+p.section_name[i]+'<td></tr>';

        o+='</table>'
        return O;
}

PHP Script

header('Content-Type: application/json');
mysql_connect('localhost','root','') ;
mysql_select_db('news');
session_start();

$query = 'select id,section_name from section';

if ($result = mysql_query($query)) {
    if (!mysql_num_rows($result)==null) {
        $myArray = array();
        while ($row = mysql_fetch_assoc($result)) {
            $id =  ToSring($row['id']);
            $myArray[] = $row;
        }

        echo json_encode($myArray);
    }
}

The database has a table named section fields are as follows

id            int(11)
section_name  varchar(20)

There are total 5 records there.

What I want is to populate a table using returned data. Can any one guide me where I am making mistake

Regards Kashif Afzaal

Be sure that mysql returns results and you can take them through ajax.

Also, I've seen the following mistake:

You are using the variable tpl wrong. It is just a js variable, no need to use $ . Use this way:

 $("#result").append(tpl);

OK, from the top in the PHP script:

  • The MySQL extension is ancient and decrepit. Use MySQLi or PDO.
  • You never handle a failed MySQL query, so the response will quite possibly be empty. In 99% of cases, any if block should have a corresponding else block.
  • The result of mysql_num_rows() is never null. Do if (mysql_num_rows($result) > 0), or better yet, just if (mysql_num_rows($result)).
  • Never do if (!something == something) - it rarely does what you want it to. Do if (something != something)
  • You never handle mysql_num_rows() failing/giving no rows, so (again) the response will quite possibly be empty.
  • You never do anything with the $id variable you create.
  • I'm pretty sure ToSring should read ToString. But there's actually no such function in PHP - you would have either define it or invoke it as a method of a class/object. Indeed, this is likely to be the problem, as it will result in a fatal error.