2

Hi the response i have an JSON :

[{"id":"1","message":"sdvsvdsdv","nickname":""},{"id":"2","message":"1234556","nickname":""},{"id":"3","message":"4555555","nickname":""}]

The javascript function :

function ajax_request(){

var request = new XMLHttpRequest();
var url = "http://localhost/chat/controller.php?showmessage";
request.open("post", url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

request.onreadystatechange = function(){
     if(request.readyState == 4 && request.status == 200){

               var return_data = request.responseText; // THE WHOLE JSON

               document.getElementById("chat").innerHTML = return_data;
        }
}
request.send();}

How can i get the element "message" only not the whole JSON ?.

Omar S.Ali
  • 45
  • 3
  • 1
    [Parse the JSON](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) into a JavaScript array, iterate over it and extract the desired data. Read [Working with Objects](https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects) if you don't know how to access properties of objects. – Felix Kling Jul 08 '12 at 15:32

3 Answers3

1

Use JSON.parse("<JSON-STRING>") to get the object out. From the object, you could extract your message.

Something like:

var jsonObj = JSON.parse(request.responseText);
for (var i=0; i<jsonObj.length; i++){
     alert(jsonObj[i].message); //alerts each "message" ..
}

This is something apart from the actual question, but I would really suggest you to use jQuery library. That takes away half of your efforts. There's a simple $.ajax(..) to do AJAX requests, and $.parseJSON(..) to parse JSON strings -- all in a cross-browser way.

UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
1
var returnObject = JSON.parse(request.responseText);
for (var i in returnObject) {
    document.getElementById("chat").innerHTML += '<br/>' + returnObject[i].message;
}
Sergey Eremin
  • 10,994
  • 2
  • 38
  • 44
  • How can i make it to show the object one time not to copy it every time when im using : setInterval(function,1000); – Omar S.Ali Jul 08 '12 at 15:32
1

Like this:

resp = '[{"id":"1","message":"sdvsvdsdv","nickname":""},{"id":"2","message":"1234556","nickname":""},{"id":"3","message":"4555555","nickname":""}]'
console.log(JSON.parse(resp)[0]['message'])

Use JSON.parse() method to convert JSON string to the JS-object

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Daniil Ryzhkov
  • 7,416
  • 2
  • 41
  • 58