0

I have this function that calls JSON from a php file

function ajax_json_data(){
    var div = document.getElementById("div");
    var hr = new XMLHttpRequest();
    hr.open("POST", "test.php", true);
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {            
            var d = JSON.parse(hr.responseText);            
                div.innerHTML += '<img src="images/'+d.num1.imageName+'" alt="'+d.num1.imageName+'" />';                    
        }
    }
    hr.send(null);
}

This is what the php file outputs

{

  "num1":{ "imageName":"img1.jpg","imgTitle":"Title1", "description":"desc1" },
  "num2":{ "imageName":"img2.jpg","imgTitle":"Title2", "description":"desc2" },
  "num3":{ "imageName":"img3.jpg","imgTitle":"Title3", "description":"desc3" }

}

My noob question is how do I target num2 from an anchor tag like;

<a href="#" onClick="ajax_json_data('num2')">Next Image</a>

I have tried

function ajax_json_data(x){

        //XMLHttpRequest

  var d = JSON.parse(hr.responseText);          
    div.innerHTML += '<img src="images/'+d.+x+.imageName+'" alt="'+d.+x+.imageName+'" />';                  

    hr.send(null);
}

but these give me errors can anyone help?

This was my solution

div.innerHTML += '<img src="images/'+d.[x].imageName+'" alt="'+d.[x].imageName+'" />';

code and learn

0 Answers0