如何从mysql表中逐行获取数据,使用jquery(AJAX)在php中编码的查询?

如何从mysql表中逐行获取数据,使用jquery(AJAX)在php中编码的查询?

问题描述:

I am a beginner in Ajax. I want to fetch data row from Subject Table consist of only one column Subject as varchar(100), defined in MySQL DB. Following is my php code.

Data.php

<?php

$con=mysqli_connect("","root","root","DBTemp") or die("</br> Error: " .mysqli_connect_error());

$sql="select * from Subject";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result))
 {
    echo $row["SUBJECT"];
    //I Want This Value to Be received in my Jquery Page
    //So that i can take certain action based on each Subject.
    //For example creating a select box child elements,options.
 }
?>

Jquery.js

$(document).ready(function()
 {
    var response='';
    $("body").ready(function()
     {
       $.ajax(
          {
            url: '/Data.php',
            type: 'GET'
            success: function(text)
                {
                     response=text;
                }
          });
     });
    $("body").append("<select> /*Get values here as options*/ </select>");
 });

But The Desired action is getting values row by row like:- 1st row value comes-> take certain action in jquery; 2nd row value comes-> take sertain action..; . . so on.

Data.php

<?php

$con=@mysqli_connect("","root","root","DBTemp");

# Instead of that use header 500 to let javascript side know there is a real error.

if (mysqli_connect_errno())
{
    echo "Could not connect to database : ". mysqli_connect_error();
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
    exit();
}


$sql="select * from Subject";

$result = mysqli_query($con,$sql);

if (mysqli_error($con))
{
    echo "Query failed : ".mysqli_error($con);
    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
    exit();
}

$options = array();

# populate options arrey with using table's id field as key 
# and subject field as value.

while($row = mysqli_fetch_assoc($result))
{
    $options[$row['id']] = $row['subject'];

}

# return json encoded array to parse from javascript.
echo json_encode($options);

Data.php will output :

{"1":"Subject ID 1","2":"Subject ID 3"}

Jquery.js

$(document).ready(function()
{

    $("body").ready(function()
    {
        $.ajax(
                {
                    url: '/Data.php',
                    type: 'GET',
                    dataType: 'json',  // Let jQuery know returned data is json.
                    success: function(result)
                    {
                        $.each(result, function(id, subject) {
                            # Loop through results and add an option to select box.
                            $("#ajaxpopulate").append( new Option(subject,id) )
                        });

                    }
                });
    });

});

Page.html , inside the body. This select box will populated from ajax request.

 <select id="ajaxpopulate"></select>

1) You need to use data structure like an array and pass it as a json response to your ajax call. 2) You need to iterate through your json array and that is where you can process each row separately and create nested select options.

UPDATE

$con=mysqli_connect("","root","root","DBTemp") or die("</br> Error: " 
.mysqli_connect_error());
$sql="select * from Subject";
$result = mysqli_query($con,$sql);
$jsonResult = [];
while($row = mysqli_fetch_assoc($result))
{
$jsonResult[] = $row["SUBJECT"];
}
echo json_encode($jsonResult);

An jquery should look like this

$(document).ready(function()

{
var response='';
$("body").ready(function()
 {
   $.ajax(
      {
        url: '/Data.php',
        type: 'GET'
        dataType : 'JSON',
        success: function(data)
            {
                 //Alert should return an array of your subjects
                 //If it does then you need to iterate through this array and create options manually.
                 alert(data);
            }
      });
 });
$("body").append("<select> /*Get values here as options*/ </select>");

});

I would have the php function return a json response. You could do this in two ways either construct the JSON manually through your while statement server side or use the json_encode PHP function and echo that server side. That way when the data is returned client side in your ajax response you can parse the JSON data to a JSON object JSON.parse(json); and then control row by row the data in a structured way.

Hope this helps!