get data from XMLHttprequest - javascript

I want to get data in json format.
I have typed this code but it doesn't return anything.
where is the problem in my code?!!
<script language="JavaScript">
var xmlhttp = new XMLHttpRequest();
var url = "http://codeforces.com/api/contest.list?gym=true";
xmlhttp.onreadystatechange = myfunction;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
function myfunction() {
if (XMLHttp.readyState == 0) {
window.alert("Uninitialized");
}
if (XMLHttp.readyState == 1) {
window.alert("loading");
}
if (XMLHttp.readyState == 2) {
window.alert("loaded");
}
if (XMLHttp.readyState == 3) {
window.alert("waiting");
}
if (XMLHttp.readyState == 4) {
window.alert("completed");
var y = JSON.parse(xmlhttp.responseText);
document.getElementById("id01").innerHTML =y[1].id;
}
}
</script>
in the html code, i have a div with id = "id01"

remember that javascript is case sensitive.
edit it to:
var xmlhttp = new XMLHttpRequest();
var url = "http://codeforces.com/api/contest.list?gym=true";
xmlhttp.onreadystatechange = myfunction;
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
function myfunction() {
if (xmlhttp.readyState == 0) {
window.alert("Uninitialized");
}
if (xmlhttp.readyState == 1) {
window.alert("loading");
}
if (xmlhttp.readyState == 2) {
window.alert("loaded");
}
if (xmlhttp.readyState == 3) {
window.alert("waiting");
}
if (xmlhttp.readyState == 4) {
window.alert("completed");
var y = JSON.parse(xmlhttp.responseText);
document.getElementById("id01").innerHTML =y[1].id;
}
}

try this:
xmlhttp.onload = function() {
if (xmlhttp.status >= 200 && xmlhttp.status < 400) {
// Success!
var data = JSON.parse(xmlhttp.responseText);
} else {
// We reached our target server, but it returned an error
}
};
disclaimer: i took this code from http://youmightnotneedjquery.com/#json

Just use fetch. It is the modern XMLHttpRequest.
const url = "http://codeforces.com/api/contest.list?gym=true";
fetch(url)
.then(
response => response.json() // .text(), etc.
// same as function(response) {return response.json();}
).then(
jsonString => {
const json = JSON.parse(jsonString);
document.getElementById("id01").innerHTML = json[1].id;
}
);
More Info:
Mozilla Documentation
Can I Use (75% Aug 2017)
Matt Walsh Tutorial

Related

Can't get all JSON to show up

It will always display the "cretetion" associated link JSON as the others are overwritten. So I tried incrementing to get all of them, but it didn't work. I don't know what I am doing wrong.
var users = ["ESL_SC2", "OgamingSC2", "cretetion"];
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
for (var i = 0; i < users.length ; i++) {
var url = "https://wind-bow.glitch.me/twitch-api/streams/" + users[i];
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
document.getElementById('online-id').innerHTML += (xmlhttp.responseText + "<br />");
}else if (xmlhttp.status == 400) {
console.log('There was an error 400');
}else {
console.log('Something else other than 200 was returned.');
}
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}
var onlineButton = document.getElementById('online-button-id');
onlineButton.addEventListener('click', loadXMLDoc, false);
I've fixed your code here:
https://plnkr.co/edit/VbkKc9QuVALAYLpujSdo?p=preview
First, the callback xmlhttp.onreadystatechange is overwritten every iteration of the loop so only the last element will be handled.
you should create and manage the XMLHttp object inside the loop, one for each element of your user array.
Secondy and most important you must wrap xmlhttp.onreadystatechange inside an Immediate invoked function otherwise each callback will use the last xmlhttp object then you will be getting the last result all the time, as you were saying above.
for (var i = 0; i < users.length ; i++) {
var xmlhttp = new XMLHttpRequest();
var url = "https://wind-bow.glitch.me/twitch-api/streams/" + users[i];
(function(xmlhttp){
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
document.getElementById('online-id').innerHTML += (xmlhttp.responseText + "<br/><br/>");
}else if (xmlhttp.status == 400) {
console.log('There was an error 400');
}else {
console.log('Something else other than 200 was returned.');
}
}
}
})(xmlhttp)
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
Try creating a new XMLHttpRequest for each iteration of the loop instead of re-using the same one. i.e.
function loadXMLDoc() {
for (var i = 0; i < users.length ; i++) {
var xmlhttp = new XMLHttpRequest();
...

How Do not call function except storage the script in local storage completed?

I do not want to call function LoadLocal(); unless the task window.localStorage.setItem( 'scriptjs', Base64.encode(xmlhttp.responseText) );
really has been completed. How?
function loadServer() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
window.localStorage.setItem( 'scriptjs', Base64.encode(xmlhttp.responseText) );
loadLocal();
}
else if (xmlhttp.status == 400) {
loadLocal();
}
else {
loadLocal();
}
}
};
xmlhttp.open("GET", "http://tokojs.com/app/hokinawafashion.js?"+Math.random(), true);
xmlhttp.send();
}
I do not want to call function LoadLocal(); unless the task window.localStorage.setItem( 'scriptjs', Base64.encode(xmlhttp.responseText) );
has been completed. How?
This is full script
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(r){var t,e,o,a,h,n,c,d="",C=0;for(r=Base64._utf8_encode(r);C<r.length;)t=r.charCodeAt(C++),e=r.charCodeAt(C++),o=r.charCodeAt(C++),a=t>>2,h=(3&t)<<4|e>>4,n=(15&e)<<2|o>>6,c=63&o,isNaN(e)?n=c=64:isNaN(o)&&(c=64),d=d+this._keyStr.charAt(a)+this._keyStr.charAt(h)+this._keyStr.charAt(n)+this._keyStr.charAt(c);return d},decode:function(r){var t,e,o,a,h,n,c,d="",C=0;for(r=r.replace(/[^A-Za-z0-9\+\/\=]/g,"");C<r.length;)a=this._keyStr.indexOf(r.charAt(C++)),h=this._keyStr.indexOf(r.charAt(C++)),n=this._keyStr.indexOf(r.charAt(C++)),c=this._keyStr.indexOf(r.charAt(C++)),t=a<<2|h>>4,e=(15&h)<<4|n>>2,o=(3&n)<<6|c,d+=String.fromCharCode(t),64!=n&&(d+=String.fromCharCode(e)),64!=c&&(d+=String.fromCharCode(o));return d=Base64._utf8_decode(d)},_utf8_encode:function(r){r=r.replace(/\r\n/g,"\n");for(var t="",e=0;e<r.length;e++){var o=r.charCodeAt(e);o<128?t+=String.fromCharCode(o):o>127&&o<2048?(t+=String.fromCharCode(o>>6|192),t+=String.fromCharCode(63&o|128)):(t+=String.fromCharCode(o>>12|224),t+=String.fromCharCode(o>>6&63|128),t+=String.fromCharCode(63&o|128))}return t},_utf8_decode:function(r){for(var t="",e=0,o=c1=c2=0;e<r.length;)o=r.charCodeAt(e),o<128?(t+=String.fromCharCode(o),e++):o>191&&o<224?(c2=r.charCodeAt(e+1),t+=String.fromCharCode((31&o)<<6|63&c2),e+=2):(c2=r.charCodeAt(e+1),c3=r.charCodeAt(e+2),t+=String.fromCharCode((15&o)<<12|(63&c2)<<6|63&c3),e+=3);return t}}
var versi = '1';
// Load Script Local
var sc = localStorage.getItem('scriptjs');
function loadLocal(){
if (sc === undefined || sc === null || sc.length === 0){
loadServer();
}
else{
var s = document.createElement('script');
s.type = 'text/javascript';
var code = Base64.decode(sc);
try {
s.appendChild(document.createTextNode(code));
document.body.appendChild(s);
} catch (e) {
s.text = code;
document.body.appendChild(s);
}
}
}
//
// Load Script Server
function loadServer() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
window.localStorage.setItem( 'scriptjs', Base64.encode(xmlhttp.responseText) );
loadLocal();
}
else if (xmlhttp.status == 400) {
loadLocal();
}
else {
loadLocal();
}
}
};
xmlhttp.open("GET", "http://tokojs.com/app/hokinawafashion.js?"+Math.random(), true);
xmlhttp.send();
}
//
window.onload = loadServer();

XMLHTTP Request post data hangs

I'm trying to create an AJAX call with the post method, and can't get it to work right. The script hangs at the processing stage (readyState does not go on to 4).
I'd appreciate it if someone could enlighten me on the issue here. I've looked at a couple of tutorials, and it seems that my code -should- work.
function newRequestPost(url, post, threadid, cfunc) {
if(window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var params = "post="+post+"&threadid="+threadid;
xmlhttp.onreadystatechange = cfunc;
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(params);
}
function openModalPreview(threadid) {
var post = document.getElementById("post_txt").value;
newRequestPost("url", post, threadid, function() {
if(xmlhttp.readyState == 1) {
document.getElementById("that_which_lies_in_the_modal").innerHTML = "Loading...";
}
if(xmlhttp.readyState == 2) {
document.getElementById("that_which_lies_in_the_modal").innerHTML = "Received";
}
if(xmlhttp.readyState == 3) {
document.getElementById("that_which_lies_in_the_modal").innerHTML = "Processing...";
}
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("that_which_lies_in_the_modal").innerHTML = xmlhttp.responseText;
}
});
}

JavaScript var outside function

How do I retrieve returndata variable outside fn() function?
function fn() {
var xmlhttp = new XMLHttpRequest();
var vars = "request=something";
xmlhttp.open("POST", "script.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var returndata = xmlhttp.responseText;
}
}
xmlhttp.send(vars);
}
You need to define global variable before function and then store the result into this variable. The way you do it now, is definition of local variable.
var returndata;
function fn() {
var xmlhttp = new XMLHttpRequest();
var vars = "request=something";
xmlhttp.open("POST", "script.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
returndata = xmlhttp.responseText;
}
}
xmlhttp.send(vars);
}
AJAX requests are asynchronous. You cannot have the pizza before it is baked. In real life you call the pizza company. They bake it and you wait. AJAX is the same. So setting the returndata won't do it all by itself.
function fn() {
var xmlhttp = new XMLHttpRequest();
var vars = "request=something";
xmlhttp.open("POST", "script.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var returndata = xmlhttp.responseText;
}
}
xmlhttp.send(vars);
}
The readystate function isn't there for nothing. It waits until the request has been processed. From there on you can go on. Every function/script that is depended on the returned data should be called upon from that function.
Still you can do this:
var returndata; //this will now be a global variable.
function fn() {
var xmlhttp = new XMLHttpRequest();
var vars = "request=something";
xmlhttp.open("POST", "script.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var returndata = xmlhttp.responseText;
doSomeThing(); //fire depended value.
}
}
xmlhttp.send(vars);
}
function doSomething()
{
if(returndata)
{
//do Something
}
else
{
alert("Data isn't loaded yet");
}
}

How will I pass a refrence of a variable, to the second funciton once the first function has called the second function inside of the first function?

In the change_text() function I am trying to pass it the xmhttp.responsetext variable.. but how will I do this? As I see no way yet on how to pass it?
<script type="text/javascript">
function ajax(url, func) {
this.url = url;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 2 && xmlhttp.status == 200) {
this.func = func;
}
}
xmlhttp.open();
xmlhttp.send()
}
function change_text() {
target = document.getElementById("x");
target.innerHTML = xmlhttp.responseText;
}
ajax("url.php", change_text);
</script>
Actually, to do this you don't want to use this at all, since you are not creating any instances of an object and it doesn't act like a constructor.
You can just:
function ajax(url, func) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// note: loaded is 4 ^
func(xmlhttp.responseText);
}
}
xmlhttp.open('GET', url, true);
// ^~~ you also forgot to pass parameters here
xmlhttp.send('');
}
That would make the ajax function work.
For your change_text function, it's not in the same function as ajax, so it does not have access to the xmlhttp variable. However, the ajax function passed the responseText to it, so just make your function receive it:
function change_text(responseText) {
var target = document.getElementById("x");
// ^~~ don't forget to declare local variables with `var`.
target.innerHTML = responseText;
}
For a working example, see the jsFiddle.
Change this.func = func; to this.func = function () { func(xmlhttp.responseText); };
<script type="text/javascript">
function ajax(url, func) {
this.url = url;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 2 && xmlhttp.status == 200) {
func(xmlhttp);
}
}
xmlhttp.open();
xmlhttp.send()
}
function change_text(xmlhttp) {
target = document.getElementById("x");
target.innerHTML = xmlhttp.responseText;
}
ajax("url.php", change_text);
</script>
You have to call your callback with parameters. Also note that this.url = url just sets window.url = url which is probably a bug.
You probably want xmlhttp.open("POST", url) instead.
Mike Samuel is almost correct, but change_text is missing an argument, try this:
<script type="text/javascript">
function ajax(url, func) {
this.url = url;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
//did you mean: func(xmlhttp.responseText);
if(xmlhttp.readyState == 2 && xmlhttp.status == 200) {
this.func = function() {
func(xmlhttp.responseText);
};
}
}
xmlhttp.open();
xmlhttp.send()
}
function change_text(responseText) {
target = document.getElementById("x");
target.innerHTML = responseText;
}
ajax("url.php", change_text);
</script>

Categories