0

Basically, i'm using an JSON response from a local PHP file to append data inside a div, currently it's only returning one variable, in which the code i'm using is shown here :

    $.ajax({
        url: "functions/ajax.php",
        data: "func=auto",
        type: "GET",
        dataType: "json",
        success: function(data){
            $.each(data.search, function (i, v) {
                    $div = $('.bs-docs-example');
                    $div.append('+ v +');
            });
        },
        error: function (jqXHR, textStatus, errorThrown){
            console.log('Error ' + jqXHR);
        }
    });

The code which is returning the JSON is currently

while($row = mysql_fetch_assoc($res)) {
     $search[] = $row['number'];
}
echo json_encode($search);

What i want to do is something like this

while($row = mysql_fetch_assoc($res)) {
     $search[] = $row['number'];
     $search[] = $row['name'];
}
echo json_encode($search);

But if i was to do the following, how would i access both number and name since in the success on the jQuery it's parsing using $.each(data.search, function (i, v) { which means the original $search[] = $row['number'] is now stored inside v

would i do something like v['name'] v['number'] or is that completely wrong ?

1 Answer 1

2

You'll want to pass an associative array to json_encode:

$search['number'] = $row['number'];
$search['name'] = $row['name'];
json_encode($search);

Or, if there will be multiple rows of results, as an array of associative arrays:

while($row = mysql_fetch_assoc($res)) {
    $search[] = $row;
}

And then access the values in JavaScript by name:

var name = v['name'];

Or

var name = v[0]['name']

If you're using multiple rows of results.

Sign up to request clarification or add additional context in comments.

3 Comments

You could just drop the while loop and do json_encode(mysql_fetch_assoc($res)), I believe, assuming there isn't a reason to only pass in those two columns specifically.
Yes you could; I left the loop in case some preprocessing needed to be done to the rows, e.g. if not all returned columns are desired in the JSON output.
Perfect exactly, with little but very exact explanations +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.