Mansa
Mansa

Reputation: 2325

Not getting json the way I want

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 :-)

Upvotes: 0

Views: 63

Answers (3)

Pluto
Pluto

Reputation: 3026

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));

});

Upvotes: 1

Kevin B
Kevin B

Reputation: 95031

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)

Upvotes: 1

Brad
Brad

Reputation: 6332

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?

Upvotes: 2

Related Questions