M M
M M

Reputation: 1

passing data from php to javascript problems with json_encode

I am kinda lost as to why I cant get data passed
javascript

jQuery.extend({
getValues: function(url) {
    var result = null;
    $.ajax({
    url: url,
    type: 'get',
    dataType: 'json',
    async: false,
    success: function(data) {

        result = JSON.stringify(data);

    }
return result;

I have no problems with the js part the problem is the php

$sql = "SELECT name, score FROM scores ORDER BY score DESC LIMIT 10 ";
$result = mysqli_query($conn1, $sql);
if (mysqli_num_rows($result) > 0) {
$data = array(); 
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = array("name"=>$row['name'], "score"=>$row['score']);
    $post_data = json_encode(array($data));
}
echo $post_data;
}

echoing post data gives nothing if i echo post data inside while loop i get a result for every iteration of while loop. If i print_r data array i also get some kind of result. My question is what am i doing wrong?
Thank you for your answers I did bring out post data from the loop that was poorly made indeed however the real problem was that one of the names was in russian alphabet and the result from database wasnt utf-8

Upvotes: 0

Views: 78

Answers (3)

M M
M M

Reputation: 1

using json_last_error I found that I couldnt encode because data wasn't utf-8

Upvotes: 0

mickmackusa
mickmackusa

Reputation: 47874

Write $post_data = json_encode(array($data)); after your while loop, otherwise you will be overwriting $post_data on each iteration.

while ($row = mysqli_fetch_assoc($result)) {
    $data[] = array("name"=>$row['name'], "score"=>$row['score']);
}
$post_data = json_encode(array($data));
echo $post_data;

I don't expect this to solve your core problem, but you did ask "what am I doing wrong".

Let us know what you get with var_export($data); after the loop and before the json_encode(). We need to see what that data & structure looks like.

Upvotes: 1

Alexis Cervetto
Alexis Cervetto

Reputation: 65

Change

result = JSON.stringify(data);

For:

result = JSON.parse(data);

Upvotes: 0

Related Questions