Quantcast
Channel: Question and Answer » json
Viewing all articles
Browse latest Browse all 148

Cannot access elements of json object

$
0
0

This is more of a json question but since it is within wordpress and is being processed by admin-ajax.php I thought it suits this forum best. I have created a standard ajax form procedure as shown below.

HTML:

<form action="" method="post" id="stock-search-form" />               
     <input class="stock-search-element" type="search" name="stock-search-name" id="stock-search-id"/>
     <input class="hide-me" type="hidden" name="action" value="process_stock" />
     <button class="stock-button" name="stock-button-name" id="stock-button-id" type="send">Search</button>                
</form>
<div class="stock-table-outer"></div>

PHP:

function process_stock() {
    $the_php_result = array("foo1" => "String_1", 
                            "foo2" => "String_2", 
                            "foo3" => "String_3", 
                            "foo4" => "String_4", 
                            "foo5" => "String_5", 
                            "foo6" => "String_6", 
                            "foo7" => "String_7", 
                            "foo8" => "String_8", 
                            "foo9" => "String_9", 
                            "foo10" => "String_10", 
                            "foo11" => "String_11", 
                            "foo12" => "String_12",
                            "foo13" => "String_13",
                            );
    echo json_encode($the_php_result);
}

JQUERY:

jQuery('#stock-search-form').submit(ajaxSubmit);

function ajaxSubmit(){

var StockSymbolUI = jQuery(this).serialize();

jQuery.ajax({
    type:"POST",
    url: "/wp-admin/admin-ajax.php",
    data: StockSymbolUI,
    success:function(data){
        jQuery(".stock-table-outer").show();
        jQuery(".stock-table-outer").html(data);
    }
});

return false;
}

The result I get returned at the front end is this:

{"foo1":"String_1","foo2":"String_2","foo3":"String_3",
"foo4":"String_4","foo5":"String_5","foo6":"String_6",
"foo7":"String_7","foo8":"String_8","foo9":"String_9",
"foo10":"String_10","foo11":"String_11","foo12":"String_12",
"foo13":"String_13"}

This at first glance looks like a json object but I dont believe it is.

What I want to do is access the elements of the object, but if I give data[0] instead of data in the success of the jquery code, all I get is {, i.e. the first character of the string. I have tried using JSON.parse(data) or jQuery.parseJSON(data) as suggested elsewhere but then I get nothing returned.

Any help would be much appreciated as I have been stuck with this for a whole day…

Harry


Viewing all articles
Browse latest Browse all 148

Trending Articles