Anurag Singh
Anurag Singh

Reputation: 727

How to display the data fetched from the database in the form

$ // First i am sending the php code which executes the sql query this code executes the query to get the data from the data base and stores all that in the get_row1 and sends it as a response to the ajax $

<?php 
    $connect = mysql_connect("localhost", "root", "");
    $data = mysql_select_db("testme", $connect);
    $identity = $_REQUEST['id'];

    $query = "SELECT * FROM student_demo WHERE id=1";
    $getdata = mysql_query($query);

    $get_row1 = mysql_fetch_array($getdata);

    $data1 = array(
            $get_row1[0],
        $get_row1[1],
        $get_row1[2],
        $get_row1[3]
    );
    print_r($data1); 
?>

$ //This sends the $data1 back to the ajax code $

if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
   xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange = function () {
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        alert(xmlhttp.responseText);
        temp1 = xmlhttp.responseText.split("=>");
        alert(temp1);
        for (var i = 0; i < 10; i++) {
        $('.data' + i).val(tmp1[i]);
            if (tmp[i] == "[0]") {
                document.getelementById("c_name").value = temp1[i];
            }
        }
    }
}

xmlhttp.open("GET", "process.php?id=" + ID, true);
xmlhttp.send();

Now what changes i should make to get the values from the array temp1 to display in the text box$

Upvotes: 2

Views: 478

Answers (1)

Viktor S.
Viktor S.

Reputation: 12815

In your php code, you should better encode response to JSON:

data1=array($get_row1[0],
        $get_row1[1],
        $get_row1[2],
        $get_row1[3]);

json_encode($data1); 

And then, in JS code, you can parse response string using JSON.parse:

if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
  alert(xmlhttp.responseText);
    temp1=JSON.parse(xmlhttp.responseText);
    console.log(temp1); // this way you can see exact structure of an object in browser console
    var i;
    for(i=0;i<10;i++)
    {
        $('.data'+i).val(tmp1[i]); // not sure what is that. If you are already using jQuery, then you can do everything even simpler
        if(tmp[i]=="[0]")
        {
            document.getElementById("c_name").value=temp1[i]; // see here getElementById - javascript is case sensitive
        }
    }

}

Note: JSON.parse is available in modern browsers only. In IE7, for instance, you will get an error because of that. To fix this problem you can download this small piece of JavaScript.

For jQuery solution take a look here

Upvotes: 1

Related Questions