Sunday, December 10, 2017

Using Json in AJAX Application

Tags

Test.php file:


<?php 

$c=new mysqli("localhost","root","naina","nearur");

$obj = json_decode($_POST["v"], false);

$sql="Select * from ".$obj->table;


$result=$c->query($sql);

if($result->num_rows>0){
   
    $r = $result->fetch_all(MYSQLI_ASSOC);//{
    //    $s .="<tr><td>".$r["name"]."</td><td>".$r["userid"]."</td></tr>";
    //}
    //$s .="</table>";
    echo json_encode($r);
}else{
    echo "0 rows";
}


?>




Test.html:

<html>
<head>
    <title>WT</title>
<script type="text/javascript">
   
function g (a) {
    var my={"table":a};
    var json=JSON.stringify(my);
    var xml=new XMLHttpRequest();
    xml.onreadystatechange=function(){
        if(this.readyState==4&& this.status==200){
            var rjson=JSON.parse(this.responseText);
           
            txt="<table border='1'>";//<tr><th>ID</th><th>Name</th><th>Email</th><th>Roll</th><th>Gender</th><th>PINCODE</th><th>Mobile</th></tr>";
            for(x in rjson){
                txt+="<tr>";
                for (h in rjson[x]) {       
                txt+="<td>"+rjson[x][h]+"</td>";
                }
                txt+="</tr>";
            }
            document.getElementById("d").innerHTML=txt;
        }
    };

    xml.open("POST","test.php",true);
    xml.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xml.send("v="+json);
   
}


</script>

</head>

<body>
    <select onchange="g(this.value)" size="1">
        <option>.....Select....</option>
        <option>Users</option>
        <option>Bank</option>
        <option>Auri</option>
        <option>Student</option>
        <option>Employees</option>
    </select>
    <p id="d">Here</p>
</body>
</html>