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.']}';
}
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. 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. Commented Jul 3, 2017 at 19:51
  • The last two lines ($table = ... and echo ...) should be after the loop. 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). 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? Commented Jul 3, 2017 at 19:59

3 Answers 3

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);
                }
            }
        });
    }
    
Sign up to request clarification or add additional context in comments.

10 Comments

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 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.
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 Paste your jQuery/AJAX and PHP code in pastebin.com and give me it's link here.
@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
|
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);

3 Comments

I also tried this but I get the error from above answer.
@User1899289003 Check your servers error log and see if it says something. What PHP version/OS are you running this on?
There is no error messages or logs, I use PHP 5.6.30
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.