1

My HTML/jQuery Code

<div id="divResult"></div>

function doSearch(str){
var jsonString = str;//$.parseJSON//JSON.stringify(str);
$.ajax({
    type:'GET',
    url:'search.php',
    data:{data:jsonString},
    success:function(data){
        for( var key in data ) {
      alert(key);
    }       
});
}

My problem is that when I tried to parse the JSON (display it) I'm not getting the expected result, The data gets displyed in a manner of per text per line eg.

The JSON data was [{"userid:1,name:paul"},{"userid:5,name:jackson"}]

The display on the browser is like this,

[
{
"
u
s
e
r
i
d
:
1

and so on so forth...

I can't understand? is there something wrong?

I tried my js code with jsFiddle and it looks good,

I expect something like these;

1 Paul
5 Jackson

PHP Code is;

if ($stmt->execute(array("%$_GET[data]%"))) {
  while ($row = $stmt->fetch()) {    
    $aResult[] = array(
        'userid'    => $row['ui_userid'],
        'category'  => $row['ui_jocategory']
        );
        //print_r($aResult);
  }  
  echo json_encode($aResult);
}

Thanks in advance..

3
  • try: alert(data[key].userid); Commented Mar 13, 2012 at 7:46
  • I think the problem is in the quotes, can you please post the var as prepared from server, and the dump of the array you are encoding? Commented Mar 13, 2012 at 7:47
  • @Vytautas: Im getting undefined as an alert Commented Mar 13, 2012 at 8:13

2 Answers 2

4

Add dataType: 'json' to your ajax options.

Sign up to request clarification or add additional context in comments.

2 Comments

i think this did the trick, however, just to fix myself, i've been trying that before but (well maybe got jumbled somewhere), why do i need the dataType option for the $.ajax?
Because your php script returns JSON data.
2

The better solution might be to add a

header('Content-Type: application/json');

at the PHP side, specifying the data type of the response. This way jQuery will automatically know to parse the response into an object without need to specify dataType: "json" from the client side.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.