javascript - Load data from table using PHP & AJAX - Stack Overflow

admin2025-04-10  0

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.']}';
}

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.']}';
}
Share Improve this question asked Jul 3, 2017 at 19:45 User1899289003User1899289003 8722 gold badges24 silver badges47 bronze badges 5
  • You're trying to parse JSON data on return, but you're not creating vaild JSON data in the PHP. Use json_encode(), never try to code JSON on your own. – Jay Blanchard Commented Jul 3, 2017 at 19:49
  • Don't build your own json-string. Just create a PHP array and encode it with json_encode() instead. – M. Eriksson Commented Jul 3, 2017 at 19:51
  • The last two lines ($table = ... and echo ...) should be after the loop. – colburton Commented Jul 3, 2017 at 19:53
  • Suggestion: Instead of substr($table, 0, strlen($table) -1), trim the string: trim($table, ','). (In other situations, that is. Here you should still use json:encode(), as mentioned). – M. Eriksson Commented Jul 3, 2017 at 19:55
  • Ok, now I get it! I'm new with PHP, one thing... how can I use json_encode() with my current code? – User1899289003 Commented Jul 3, 2017 at 19:59
Add a ment  | 

3 Answers 3

Reset to default 4

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 ing 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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744275171a239210.html

最新回复(0)