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.']}';
}
User1899289003
  • 850
  • 2
  • 21
  • 40
  • 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 Jul 03 '17 at 19:49
  • Don't build your own json-string. Just create a PHP array and encode it with [json_encode()](http://php.net/manual/en/function.json-encode.php) instead. – M. Eriksson Jul 03 '17 at 19:51
  • The last two lines ($table = ... and echo ...) should be after the loop. – colburton Jul 03 '17 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 Jul 03 '17 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 Jul 03 '17 at 19:59

3 Answers3

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 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);
                }
            }
        });
    }
    
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
  • I made the changes but now I don't get any type of information (from echo json_encode) and there is no error messages too – User1899289003 Jul 03 '17 at 20:15
  • @User1899289003 Couple of things to debug here, 1) Did you call this `LoadProductos()` function? 2) Do `alert(data);` in the `success` callback function and see what you're getting there. – Rajdeep Paul Jul 03 '17 at 20:18
  • Yes! I'm calling my function and also I alert(data), I also open browser console to see what's happen and the function is executed fine, but in Preview/Response window there is nothing, I change echo json_encode($table) to echo "hello" and works properly. – User1899289003 Jul 03 '17 at 20:23
  • @User1899289003 Paste your jQuery/AJAX and PHP code in [pastebin.com](https://pastebin.com/) and give me it's link here. – Rajdeep Paul Jul 03 '17 at 20:25
  • @User1899289003 You didn't include `dataType: 'json'` setting in your AJAX request. There are actually two ways you can achieve your desired result, both ways are listed here(*LoadProductos* function), [https://pastebin.com/WxuTffZh](https://pastebin.com/WxuTffZh) – Rajdeep Paul Jul 03 '17 at 20:39
  • I change my code but I'm still getting an empty array! – User1899289003 Jul 03 '17 at 20:43
  • Ready! The code it's ok, the problem was that I have special characters and this broke the json_encode(), there is a way to avoid this? – User1899289003 Jul 03 '17 at 20:56
  • @User1899289003 Not sure what those special characters are but your input has to be encoded as `UTF-8` or `ISO-8859-1`. There are couple of SO threads on this issue, for example: https://stackoverflow.com/q/20694317/5517143 and https://stackoverflow.com/q/7284535/5517143 – Rajdeep Paul Jul 03 '17 at 21:08
  • Ready! I just made this: utf8_encode($row['Name']), btw... special characters are this á, ó, something like that. Thanks for your help buddy! – User1899289003 Jul 03 '17 at 21:18
  • @User1899289003 You're welcome! Glad I could help. :-) – Rajdeep Paul Jul 03 '17 at 21:20
2

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);
M. Eriksson
  • 13,450
  • 4
  • 29
  • 40
0

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.