No response when using AJAX and JSON - javascript

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.

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.

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.

Related

why fail to request url in ajax when

this is my ajax code
function buatajax(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function checkout() {
var url = "index3.php";
url = url+"&sid="+Math.random();
ajaxku = buatajax();
ajaxku.onreadystatechange=checkoutisi;
ajaxku.open("GET",url,true);
ajaxku.send(null);
}
function checkoutisi() {
if(ajaxku.readyState == 4){
data = ajaxku.responseText;
document.getElementById('isiecon').innerHTML = data;
alert(data);
}
}
when i alert data as it's shown, it said that the requested url not found.
I'm using localhost server for now, instead of using jquery ajax, how to use ajax in my way? because i dont really understand the jquery ajax way.

return value = undefined when i try to call a Ajax-function inside another Ajax-function

i have a function with a XML-HTTP-Request. Unfortunately i don't get back my DB-result when i call this function getUserdataByToken() <-- working, via a second Function sendPost(wall).
I just want to have the return value (array) inside my second function but the value is always "undefined". Can someone help me?
function getUserdataByToken() {
var token = localStorage.getItem("token");
var userDataRequest;
//-AJAX-REQUEST
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var url= window.location.protocol+"//"+window.location.host+"/getuserdatabytoken";
var param = "token=" + token;
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
userDataRequest = JSON.parse(xhttp.responseText);
if (userDataRequest.success === "false") {
warningMessage('homeMessage', false, userDataRequest.message);
} else {
return userDataRequest;
}
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(param);
}
Function call via second Function (AJAX) leads too "undefined" Value for "userDataRequest" (return of function 1).
function sendPost(wall) {
var content;
var token = localStorage.getItem("token");
var userData = getUserdataByToken(); // PROBLEM
console.log(userData); // "leads to undefined"
alert(userData); // "leads to undefined"
… Ajax Call etc…
P.S. it's my first post here in stackoverflow, I'm always grateful for tips.
Thanks!
The userdata value only exists within the anonymous Ajax callback function, and you only return it from there. That is pointless because there is nowhere for it to be returned to; certainly the value does not get returned from getUserdataByToken. Don't forget that Ajax calls are asynchronous; when sendPost calls getUserdataByToken the request won't even have been made.
Generally you'd be much better off using a library like jQuery for this whole thing. Apart from making your code much simpler, it will allow you to use things like Promises which are explicitly intended to solve this kind of problem.
(And, do you really need to support IE5? Are you sure?)

Getting AJAX to Work With JavaScript

Just to point out, I know how to do this with jQuery and AngularJS. The project I am currently working on requires me to use plain JavaScript.
I'm trying to get AJAX to work with just plain JavaScript. I am using Java/Spring for backend programming. Here is my JavaScript code:
/** AJAX Function */
ajaxFunction = function(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.status == 200) {
var JSONResponse = JSON.parse(xhttp.responseText);
return JSONResponse;
}
}
xhttp.open('GET', url, true);
xhttp.send();
}
/** Call Function */
searchResults = function() {
var test = ajaxFunction('http://123.456.78.90:8080/my/working/url');
console.log(test);
}
/** When the page loads. */
window.onload = function() {
searchResults();
}
It's worth noting that when I go directly to the URL in my browser's address bar (example, if I go directly to the link http://123.456.78.90:8080/my/working/url), I get a JSON response in the browser.
When I hover over xhttp.status, the status is saying 0, not 200, even though I know that the link I am calling works. Is this something that you have to set in Spring's controllers? I didn't think that was the case because when I inspect this JS URL call in the Network tab, it states that the status is 200.
All in all, this response is coming back as undefined. I can't figure out why. What am I doing wrong?
An XMLHttpRequest is made asynchronously meaning that the request is fired off and the rest of the code continues to run. A callback is provided and when the asynchronous operation completes the callback function is called. The onreadystatechange function is called upon completion of an AJAX request. In your example the ajaxFunction will return immediately after the xhttp.send() line executes, so your var test won't have the JSON in it as I assume you expect.
In order to do something when an AJAX request completes you need to use a callback function. If you wanted to log the result to the console as above you could try something like the following:
var xhttp;
var handler = function() {
if(xhttp.readyState === XMLHttpRequest.DONE) {
if (xhttp.status == 200) {
var JSONResponse = JSON.parse(xhttp.responseText);
console.log(JSONResponse);
}
}
};
/** AJAX Function */
var ajaxFunction = function(url) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = handler;
xhttp.open('GET', url, true);
xhttp.send();
};
/** Call Function */
var searchResults = function() {
ajaxFunction('http://123.456.78.90:8080/my/working/url');
};
/** When the page loads. */
window.onload = function() {
searchResults();
};
If you want to learn more about how XMLHttpRequest works then MDN is a much better teacher than I am :)

How to set multiple HTTP headers in JavaScript get () method

I have been searching the total Internet from around a week and finally decided to post here. I want to send an HTTP get request to an API with two headers for authentication. These are custom headers and need to be sent at once.
I have tried the following code but it never gives me success. The API returns a JSON file which will have parameters like "title", "description". The URL and headers work fine, when I tried it using hurl.it.
This is the code. Please suggest some answer to solve this problem. And one more thing is, I want to do it using JavaScript only, no jQuery, AJAX, or AngularJS.
var xmlhttp = new XMLHttpRequest();
var url = "https://affiliate- api.flipkart.net/affiliate/offers/v1/dotd/json";
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 &&xmlhttp.status==200) {
var myArr = JSON.parse(xmlhttp.responseText);
function display(arr) {
var i;
var out = " ";
for(i = 0; i < arr.length;i++) {
out += "<p>title:" + arr.dotd[i].title + "<br>description:" + arr.dotd[i].description + "<br></p>";
}
document.getElementById("p1").innerHTML = out;
}
}
else {
alert(xmlhttp.status);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Fk-Affiliate- Token","xxxxxxxxxxxxxxxxx");
xmlhttp.setRequestHeader("Fk-Affiliate-Id","xxxxxxxxx");
xmlhttp.send();

Ajax multiple drop down list

I have 5 drop down lists which is dynamic in nature. But the only problem is all the option values are being fetched from mysql database and i really want the user to know that the query is happening at the backend and he should wait by displaying a gif or a line saying "loading.. " .
I've been looking all over for this and similar questions have been posted by others but i don't seem to get it working . Please help me out. Can somebody please give a easy solution?
Thanks.
I've placed an example here:
http://jsfiddle.net/cMEaM/embedded/result/
I've kept as much of the existing code the same so you should still recognise it. The getXMLHTTP function is the same:
function getXMLHTTP() {
//function to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
There's a new sendGet function to handle the XHR request, which takes success and error callbacks.
function sendGet(url, onSuccess, onError) {
var req = getXMLHTTP();
var method = "GET";
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
onSuccess(req);
} else {
onError(req);
}
}
}
req.open(method, url, true);
req.send(data);
}
}
I borrow a throbber from Wikipedia to display when the data is loading.
var throbberHtml = "<img src='http://upload.wikimedia.org/wikipedia/en/2/29/Throbber-Loadinfo-292929-ffffff.gif'>";
And these are the new getXXX functions which replace the <select> with the throbber while the data is loading:
function getState(countryId) {
var div = document.getElementById('statediv');
var oldInnerHTML = div.innerHTML;
var onSuccess = function(req) {
div.innerHTML = req.responseText;
};
var onError = function(req) {
div.innerHTML = oldInnerHTML;
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
};
div.innerHTML = throbberHtml;
sendGet("findState.php?country=" + countryId, onSuccess, onError);
}
function getCity(countryId, stateId) {
var div = document.getElementById('citydiv');
var oldInnerHTML = div.innerHTML;
var onSuccess = function(req) {
div.innerHTML = req.responseText;
};
var onError = function(req) {
div.innerHTML = oldInnerHTML;
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
};
div.innerHTML = throbberHtml;
sendGet("findCity.php?country=" + countryId + "&state=" + stateId,
onSuccess, onError);
}
There are other improvements that could be made, but I tried to keep in the sprit of your existing code as much as possible.
E.g. you can see that most of code in the getXXX functions is the same, so you could refactor these to use mostly the same code. Also, using a JS framework such as jQuery will replace the XHR code with better, more cross-browser compatible code. It's usually always better to avoid reinventing the wheel when it comes to code!
And you may possibly decide that sending the HTML for a <select> tag is not the best data format for the XHR. You might go with JSON which would decouple your presentation from the data.

Categories