0

I have this Ajax request with jquery:

$(document).ready(function () {
    var pageName;

    $('li a').on('click', function (){
        pageName = $(this).attr('data-url');

        $.ajax({
            type: 'GET',
            url: 'http://mywebsite.com/' + pageName + '/?json=1',
            contentType: 'application/json',
            dataType: 'jsonp',
            success: function(data) {
                var page = data.content;
                $('.mypage').html(page);
            }
        })
    });
});

And i want change to XMLHttpRequest, so i did this:

function showPage () {

    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4) {
            document.getElementById('.mypage').innerHTML = httpRequest.responseText;
        }
    };

    var attr = document.getElementByTagName(this);
    var pageName = attr.getAttribute('data-url');
    var url = 'http://mywebsite.com/' + pageName + '/?json=1',

    httpRequest.open('GET', url);
    httpRequest.send();
}

It's not working at all, anyone knows what i did wrong?

  • open(method,url,async) Specifies the type of request, the URL, and if the request should be handled asynchronously or not. method: the type of request: GET or POST url: the location of the file on the server async: true (asynchronous) or false (synchronous) you missing one parameter in open() function – Anik Islam Abhi Oct 25 '14 at 03:33
  • the 3rd argument to open() defaults to true if omitted. – dandavis Oct 25 '14 at 04:19

1 Answers1

0

This line is wrong:

document.getElementById('.mypage').innerHTML = httpRequest.responseText;

A selector beginning with . is a class selector, not an ID. It should be:

document.getElementsByClassName('mypage')[0].innerHTML = httpRequest.responseText;

I'm assuming you only have one element with this class. If there are multiple, you need to change that to a loop that sets them all.

However, you can't use XMLHttpRequest with JSONP dataType. See

JavaScript XMLHttpRequest using JsonP

for how to implement JSONP with raw Javascript.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612