DOGGIES52
DOGGIES52

Reputation: 27

How to update url via javascript in the XMLHTTPRequest

I'm trying to update the URL inside my javascript function e.g.

http://tmaserv.scem.uws.edu.au/chapters/?n=0
http://tmaserv.scem.uws.edu.au/chapters/?n=1

and so on.
I've tried using a for loop but it hasn't work.

Javascript:

function do_exercise () {
    var x = new XMLHttpRequest();{
        x.open('GET', 'http://tmaserv.scem.uws.edu.au/chapters/?n=0', true);
        x.onreadystatechange = function() {
            if (x.readyState == 4 && x.status ==200) {
                obj = (x.responseText);
                JSON.parse(x.responseText);
                obj = JSON.parse(obj);
                document.getElementById("section1").innerHTML =
            obj.data
            }
        }
        x.send(null);
    }
}

HTML:

<nav>           
    <button onclick="do_exercise();">Next section</button>      
</nav>
<section id = "section1">
    <h1>Heading One</h1>
    <p>Paragraph One.</p>
</section>

Upvotes: 0

Views: 268

Answers (1)

Rory O&#39;Keeffe
Rory O&#39;Keeffe

Reputation: 211

You could do something like this:

var requestNum = 0;

function do_exercise () {
    var x = new XMLHttpRequest();
    // adjust the GET URL to reflect the new n value and request as before
    x.open('GET', 'http://tmaserv.scem.uws.edu.au/chapters/?n=' + requestNum, true);
    x.onreadystatechange = function() {
        if (x.readyState == 4 && x.status ==200) {
            obj = (x.responseText);
            JSON.parse(x.responseText);
            obj = JSON.parse(obj);
            document.getElementById("section1").innerHTML = obj.data;
            requestNum++;
        }
    }

    x.send(null);
}

Does that make sense? Note that I have removed some curly braces that I presume were a mistake on this line var x = new XMLHttpRequest();{.

I would also recommend using jQuery.getJSON for your AJAX call for better browser compatibility and cleaner code.

EDIT: Made my answer far simpler. Thanks to Robert for pointing out where I was completely overthinking things!

Upvotes: 2

Related Questions