0

I am trying to send or retrieve, not sure where the fault is, in a specific way...

Here is how it should look when using JSON.stringify(test):

{"1":"<div class=\"test\">test1</div>","2":"<div class=\"test\">test2</div>","1":"<div class=\"test\">test1</div>"}

But my ajax/json return looks like this:

["'1':'<div class='test'>test1</div>'","'2':'<div class='test'>test2</div>'","'3':'<div class='test'>test3</div>'"]

I need curly brackets at the beginning and " not to be there.

Here is how I send and get data.

test.php

$test = array();

$test[] = array('id' => '1', 'name' => 'test1');
$test[] = array('id' => '2', 'name' => 'test2');
$test[] = array('id' => '3', 'name' => 'test3');

echo json_encode($test);

And the javascript which retrieves it:

var mytest = [];

$.getJSON('test.php', function(data){ 

    $.each(data, function (i, val) {
        mytest.push("'"+val.id+"':'<div class='test'>"+val.name+"</div>'");
    });

    alert(JSON.stringify(mytest));

});

Really hoping for help... I am stuck. Thanks in advance :-)

usercode
  • 309
  • 4
  • 20
Mansa
  • 2,277
  • 10
  • 37
  • 67
  • 2
    You are creating an array, and expect it to start with `{`? that simply won't happen. arrays start with `[` in javascript. – Kevin B Jul 17 '13 at 18:30
  • So what I am trying to accomplish can't be done? – Mansa Jul 17 '13 at 18:33
  • It can be done, it just wouldn't be very useful as an array. If you wanted an array, you should just keep what you already have in `data` as-is. – Kevin B Jul 17 '13 at 18:41

3 Answers3

2

you're using an array. As Kevin noted, that won't work. you need to declare an object literal which expects key value pairs.

ie

var myTest = {}; 

$.each(data, function (i, val) {
  mytest[i] = val;
});

This is a good and more detailed explanation. How can I add a key/value pair to a JavaScript object?

Community
  • 1
  • 1
Brad
  • 6,106
  • 4
  • 31
  • 43
1

Most likely what you really want is just an object.

var mytest = {};
$.each(data, function (i, val) {
    mytest[val.id] = "<div class='test'>"+val.name+"</div>";
})

Note, i purposely moved var mytest into the ajax callback because there's no reason to define it outside (it won't be useable outside of the callback)

Kevin B
  • 94,570
  • 16
  • 163
  • 180
1

In your JavaScript code, you're creating an array in your results instead of an object... So instead of using [], you should use {} and instead of using .push, you should directly assign the attributes of the object with mytest["1"] = whatever. So here's a modified form of your code...

var mytest = {};

$.getJSON('test.php', function(data){ 

    $.each(data, function (i, val) {
        mytest[val.id] = '<div class="test">'+val.name+'</div>';
    });

    alert(JSON.stringify(mytest));

});
Pluto
  • 2,900
  • 27
  • 38