Ben Ewan
Ben Ewan

Reputation: 3

No response when using AJAX and JSON

function getIDs() {
alert("1");
var title = document.getElementById('title').value;
alert(title);
title = "http://www.imdbapi.com/?i=&t=" + title;
alert(title);
xmlhttp=new XMLHttpRequest();
alert("2");
xmlhttp.open("GET",title,true);
alert("3");
xmlhttp.send();
alert("4");
var imdbData = xmlhttp.responseText;
alert(imdbData);
var imdbJSON = JSON.parse(imdbData);
//document.getElementById('title').value = imdbJSON.Title;
alert(imdbJSON.Title);
document.getElementById('imdbid').value = imdbJSON.ID;
return true;
}

I'm trying to fetch the ID of a film based upon it's title, the function gets called successfully and the alerts are correct until the alert which returns "imdbData", which returns a blank alert, then no more alerts occur, I'm unsure where I'm going wrong here. Any assistance would be appreciated.

Upvotes: 0

Views: 306

Answers (2)

Repox
Repox

Reputation: 15476

You are not allowed to do cross site scripting with JavaScript which is why you get nothing in return. You need to be on the same domain as you post your AJAX call to.

Use a serverside script to parse the URL for you instead.

Upvotes: 0

icktoofay
icktoofay

Reputation: 129109

You're opening it asynchronously. To make it synchronous, change this:

xmlhttp.open("GET",title,true);

To this:

xmlhttp.open("GET",title,false);

A usually-considered-better way would be to make it work with asynchronicity:

function getIDs() {
    alert("1");
    var title = document.getElementById('title').value;
    title = "http://www.imdbapi.com/?i=&t=" + title;
    xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function() {
        if(xmlhttp.readyState==4) {
            var imdbData = xmlhttp.responseText;
            var imdbJSON = JSON.parse(imdbData);
            document.getElementById('title').value = imdbJSON.Title;
            document.getElementById('imdbid').value = imdbJSON.ID;
        }
    };
    xmlhttp.open("GET",title,true);
    xmlhttp.send();
    return true;
}

Additionally, you cannot request pages from other domains. You may need to switch to JSONP if the API you're using supports it, or use your web server as a proxy.

Upvotes: 1

Related Questions