useranon
useranon

Reputation: 29514

Missing ) in parenthetical expression while receiving AJAX response JSON via JQuery

In JQuery ajax Get I am using the following,

var htm = $.ajax({
    type: "GET",
    url: "http://localhost/cake_1.2.1.8004/index.php/forms/getFormEntry",
    async: false
}).responseText;

alert(htm);

var myObject = eval('(' + htm + ')');

alert(myObject);

My cakePHP code for getFormEntry is

$data = array();
foreach ($formid as $r): 
    array_push($data, array('id' => $r['Form']['id']));
endforeach; 
echo json_encode(array("attributes" => $data));

My alert(htm) shows

Array{"attributes":[{"id":"21"},{"id":"20"},{"id":"19"},{"id":"18"},{"id":"17"},{"id":"16"},{"id":"15"},{"id":"14"},{"id":"13"},{"id":"12"},{"id":"11"},{"id":"10"},{"id":"9"},{"id":"8"},{"id":"7"},{"id":"6"},{"id":"5"},{"id":"4"},{"id":"3"},{"id":"2"},{"id":"1"}]}

I want to get the attributes id -21. For that I have used the myObject but showing the error as missing ) in parenthetical.

Please suggest how to fix this.

Upvotes: -1

Views: 103

Answers (1)

Yehuda Katz
Yehuda Katz

Reputation: 28703

You want to be using jQuery's built-in JSON support. Also, you probably don't want to be using synchronous Ajax. Try the following; the function will be called once the Ajax request is complete, and you will have access to a JavaScript object as "json" in the function.

$.getJSON("http://localhost/cake_1.2.1.8004/index.php/forms/getFormEntry", function(json) {
  // access to object here as "json". No need to mess with eval
})

Upvotes: 2

Related Questions