0

I am getting a multidimensional array in form of JSON from a php file as AJAX response , there are two values I am getting from it , name and email , I need to update name and email of two respective divs each 5 seconds.

PHP response in JSON form: {"sophia":"[email protected]"}

Below is my javascript code:

window.setInterval(function () {
            var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var data = JSON.parse(xmlhttp.responseText);
                for (var index in links) {
              //update name div
               document.getElementById("name").innerHTML= links[index]; 
             //update email div
               document.getElementById("email").innerHTML= links[index];
                  }
                }
            }
            xmlhttp.open("GET", "get_data.php", true);
            xmlhttp.send(); 
        }, 5000);

My html code:

<div id="name"></div>
<div id="email"></div>
4
  • Should it not be document.getElementById("name").innerHTML= index;? Commented Oct 19, 2015 at 16:26
  • So, whats the problem? You said your background, your goal, your attempt... what's wrong? Commented Oct 19, 2015 at 16:26
  • JSON === JavaScript Object Notation. What you have is a JS object, not an array. links.sophia will get you the email, if you don't know what the properties will be, for (var p in links) { if (links.hasOwnProperty(p)) links[p]; is how you should iterate over a JS object Commented Oct 19, 2015 at 16:34
  • @EliasVanOotegem Thanks, now I realized it :) Commented Oct 19, 2015 at 16:42

1 Answer 1

4

Since your Object looks like {"sophia":"[email protected]"}; Change it to:

....
document.getElementById("name").innerHTML= index;   //sophia
         //update email div
document.getElementById("email").innerHTML= links[index];  //obj['sophia']= [email protected]
....

http://jsfiddle.net/sandenay/r0hry8x0/

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.