简体   繁体   中英

Load data from table using PHP & AJAX

I'm trying to retrieve data from table using PHP and AJAX, at the moment I'm able to display the result of my query in json format, what I want to do is select an specific data from that array, for example I get this array:

{data: [{IdProduct: "1", Name: "Name here..........",…}]}

For example I want to select only Name, I tried doing this:

function LoadProductos() {

$.ajax({
    url: '../../class/loadProd.php',
    method: 'POST',
    success: function (data) {
      var aRC = JSON.parse(data);

      for (var i = 0; i < aRC.length; i++) {
        console.log(aRC[i].Name);
      }
    }

  });
}

But this doesn't shows anything, how can I do this? This is my PHP code:

while($row = mysqli_fetch_array($registros)) {

    $table.='{
        "IdProduct":"'.$row['IdProduct'].'",
        "Name":"'.$row['Name'].'",
        "Description":"'.$row['Description'].'",
        "ImagePath":"'.$row['ImagePath'].'"
    },';

    $table = substr($table, 0, strlen($table) -1);

    echo '{"data":['.$table.']}';
}

There are couple of things you need to change in your code, such as:

  • That's not how you should create a json string. Create an empty array before the while() loop and append the row details to this array in each iteration of the loop. And after coming out of the loop, simply apply json_encode() function to the resultant array to get the final json string.

     $table = array(); while($row = mysqli_fetch_array($registros)) { $table[]= array( 'IdProduct' => $row['IdProduct'], 'Name' => $row['Name'], 'Description' => $row['Description'], 'ImagePath' => $row['ImagePath'] ); } echo json_encode($table); 
  • Since you're expecting a json string from server, add this setting dataType:'json' to your AJAX request. dataType is the type of data you're expecting back from the server. And in the success() callback function, simply loop through the json result to get the relevant data.

     function LoadProductos() { $.ajax({ url: '../../class/loadProd.php', method: 'POST', dataType: 'json', success: function (data) { for (var i = 0; i < data.length; i++) { alert(data[i].Name); } } }); } 

First off, your shouldn't echo the json data in the loop. It should be outside the loop. You shouldn't build your own json data either.

Let's build an array that looks like the json response you want. Then we'll use the function json_encode() to encode it as a proper json-string:

// Define the response array
$response = [
    'data' => []
];

while($row = mysqli_fetch_array($registros)) {

    // Push a new array to 'data' array
    $response['data'][] = [
        'IdProduct'   => $row['IdProduct'],
        'Name'        =>.$row['Name'],
        'Description' => $row['Description'],
        'ImagePath'   => $row['ImagePath']
    ];
}

// Now, let's encode the data:
echo json_encode($response);

In you PHP file make changes according to this:-

$outp = array();
$outp = $res->fetch_all(MYSQLI_ASSOC);

For make sure that json_encode don't return null

function utf8ize($d) {
 if (is_array($d)) {
    foreach ($d as $k => $v) {
        $d[$k] = utf8ize($v);
    }
} else if (is_string ($d)) {
    return utf8_encode($d);
}
return $d;
}
echo json_encode(utf8ize($outp));

You JavaScript is okay You just need to change code in PHP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM