0

I use jquery and ajax to retrieve a dynamically made array made in php, like so:

$json = array();

while ($row = $stmt->fetch_assoc()) {

    $json['item_'.$row['id']] = $row['name'];
}

header('Content-type: application/json; charset=utf-8');
echo json_encode($json);
exit;

If I test the php file in browser, it outputs:

{"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"}

So far so good. But how do I use that array in jquery?

I have this jquery ajax:

$.getJSON( "json.php", function(data) {
    console.log(data);
});

And testing that page in browser, it put this in console:

Object {item_3: "Simon", item_1: "Miriam", item_2: "Shareen"}

And that's ok right? Or should item_x also be in quotes?

Now, how do I USE that array in jquery?

If I try console.log(data[0]) it puts undefined

7
  • javascript does not have associative arrays - this is a javascript object, properties are accessed with . console.log(data.item_3); Commented Jul 3, 2014 at 11:03
  • I'm not targeting item_3. I want to use the first key and value (array is randomly made) Commented Jul 3, 2014 at 11:04
  • 1
    @mowgli — There isn't a first key, objects are unordered. Commented Jul 3, 2014 at 11:06
  • hm. Maybe I should make each value-pair an array itself, in php.. that seemed to work some Commented Jul 3, 2014 at 11:08
  • May be your sever does not return an array of Objects. Plz check that. Commented Jul 3, 2014 at 11:09

2 Answers 2

1

As i mentioned in comments, php associative arrays become javascript objects, which cant be accessed numericaly.

A solution would be to send an array of objects instead:

while ($row = $stmt->fetch_assoc()) {

    $json[]= ['key'=>'item_'.$row['id'] , 'value' => $row['name']];
}

the in js:

data[0].key;
data[0].value;

EDIT obviously key is a misleading name in this example, better to call it something else:

$json[]= ['id'=>'item_'.$row['id'] , 'value' => $row['name']];
//js
data[0].id;
Sign up to request clarification or add additional context in comments.

4 Comments

Ah yes, got to try this.. Edit: Hmm, Parse error: syntax error, unexpected ','
I had to edit it into: $json[] = ['key' => $row['id'] , 'value' => $row['name']]; There was missing surrounding brackets
Even better: $json[] = [$row['id'] => $row['name']]; I don't need to set id/value :) Edit: hm or maybe I do.. console.log(data[0][0]) is undefined, but data[0] works.. But I'm getting closer!
@mowgli thank, fixed missing bracket, and you do need to set them as property names if you want to access the value of both in js.
1

Try to use $.each() to iterate through that object,

$.each(data,function(key,val){
  console.log(key,val);
});

DEMO

If you want to access it without iterating it then simply use bracket notation

data['item_3'] //Simon

Or directly access it like,

data.item_3 //Simon

Then convert it like an array as per your wish like this,

var obj = {"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"};

var convertedArray = $.map(obj,function(val,key){
    var obj = {}; obj[val] = key;
    return obj;
});

DEMO

7 Comments

Yes, I also tried this. I worked.. but do I really need to use each for an array and re-make an array so I can use that? Let's say I want to use $("#mydiv").html(first_key_and_var_in_array);
@mowgli what are you trying to do..?
I'm trying to build a very simple content changer/slider.. It should just replace a div with content from first array key/value, then wait 5 seconds, then replace with next array set. Something like that
@mowgli Then declare a counter and increment it for every slide, and access the values like data['item_'+counter]
Yes, hmm.. But the item_xx can be any number. AND the array is in random order (on purpose)
|

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.