An AJAX call with JavaScript - javascript

I'm trying to learn how to make an AJAX call using vanilla JavaScript in an effort to move away from JQuery for a little project that I'm working on but don't seem to be getting past xmlhttp.onreadystatechange. Can anyone point to what I'm doing wrong (the function getDVDsAndBluRays() is getting invoked on DOMContentLoaded)? Thanks!
function getDVDsAndBluRays() {
console.log("Getting logged");
var xmlhttp = new XMLHttpRequest();
var url = 'http://www.omdbapi.com/?t=metropolis&y=&plot=short&r=json';
xmlhttp.onreadystatechange = function() {
console.log("Not getting logged");
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('responseText:' + xmlhttp.responseText);
var myMovies = JSON.parse(xmlhttp.responseText);
myFunction(myMovies);
}
xmlhttp.open('GET', url, true);
xmlhttp.send();
};
}
function myFunction(myMovies) {
for (var i = 0; i < myMovies.length; i++) {
var title = myMovies[i].Title.toLowerCase().split(' ').join('+');
var year = myMovies[i].Year;
console.log(title + ", " + "year");
}
}

It should be like that, notice the location of open and send functions:
function getDVDsAndBluRays() {
console.log("Getting logged");
var xmlhttp = new XMLHttpRequest();
var url = 'http://www.omdbapi.com/?t=metropolis&y=&plot=short&r=json';
xmlhttp.open('GET', url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
console.log("Not getting logged");
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('responseText:' + xmlhttp.responseText);
var myMovies = JSON.parse(xmlhttp.responseText);
myFunction(myMovies);
}
};
}
function myFunction(myMovies) {
for (var i = 0; i < myMovies.length; i++) {
var title = myMovies[i].Title.toLowerCase().split(' ').join('+');
var year = myMovies[i].Year;
console.log(title + ", " + "year");
}
}
onreadystatechange is executed after the call, you were actually "calling the service when it replies"

You have your .open() and .send() inside your onreadystatechange() handler. Put those outside of the onreadystatechange function and you should be good to go.
Onreadystatechange() is the event handler for when there is a change in state in the xmlhttp request, and will not get called until you open the request and send it.
Hope this helped!

You have put the calls to open and send inside the onreadystatechange event handler so they will never be called.
Move them outside it.

Related

Firebase Cloud Function Warning (Function returned undefined, expected Promise or value)

I just set up a cloud function triggered by a sub/pub topic. The function triggers an HTTP-triggered cloud function by, well, making a GET request. It all works well, the only thing that doesn't quite line up is a warning message
Function returned undefined, expected Promise or value
I have to admit I'm not as fluent in promises as I should be, and that might be the reason for the error. Here is the Node code.
exports.triggerClearHidden = functions.runWith(global.runtimeOptions).pubsub.topic('trig').onPublish((message) => {
// const pubsubMessage = message.data;
// console.log(Buffer.from(pubsubMessage, 'base64').toString());
let urlstr = functions.config().rain.projecturl + "/clearHidden";
httpGetAsync(urlstr, (txt => console.log(txt)));
});
function httpGetAsync(theUrl, callback)
{
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200){
return callback(xmlHttp.responseText);
} else {
return callback("the ready state is " + xmlHttp.readyState + " and the status is " + xmlHttp.status);
}
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}

Somehow this won't show me an alert or any errors

somehow this code just blanks and isn't really doing anything.
Doesn't even show any errors.
So can Someone help?
function connectStart(mycon){ //connection start for contacting
return function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonReturn = JSON.parse(this.responseText);
mycon; //calls the makeAnn() Function
}
};
// mypref() stands for the preference code location for the myphp.php
xmlhttp.open("GET", mypref()+"myphp.php?q="+myvar,true);
xmlhttp.send();
}
}
function makeAnn(){
return function(){
console.log(jsonReturn);
if ( jsonReturn !== "NO"){
alert("Announcement Was Posted");
} else {
alert("Error Encoding Data");
}
} //end of return function()
}
function mainFunction(){ //is called by an onclick event
var myvar = "I Shall Return!";
connectStart(makeAnn()); // i used invocation to combine them
}
Somehow it never shows any actual complaints or anything on the console log.
No alerts or whatever.
Doesn't write the data sent to the php or database.
No nothing really.
And I have tried the Php and html, their both fine.
It's just this part of my code that won't work.
You are not calling the function inside your onreadystatechange handler. See below.
function connectStart(mycon){ //connection start for contacting
return function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonReturn = JSON.parse(this.responseText);
// mycon; //wouldn't do anything
mycon(); // THIS should work better...
}
};
// mypref() stands for the preference code location for the myphp.php
xmlhttp.open("GET", mypref()+"myphp.php?q="+myvar,true);
xmlhttp.send();
}
}
EDIT:
The other problem which I now noticed is that you are referencing jsonReturn way, way out of its scope.
function connectStart(mycon){ //connection start for contacting
return function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonReturn = JSON.parse(this.responseText);
mycon(jsonReturn); // pass jsonReturn as a parameter
}
};
// mypref() stands for the preference code location for the myphp.php
xmlhttp.open("GET", mypref()+"myphp.php?q="+myvar,true);
xmlhttp.send();
}
}
function makeAnn(){
return function(jsonReturn){ // pass in as a parameter
console.log(jsonReturn);
if ( jsonReturn !== "NO"){
alert("Announcement Was Posted");
} else {
alert("Error Encoding Data");
}
} //end of return function()
}
function mainFunction(){ //is called by an onclick event
var myvar = "I Shall Return!";
connectStart(makeAnn()); // i used invocation to combine them
}

Doing multiple XMLHttpRequest from different url

I'm trying to use XMLHttpRequest to get data from two different localhost ports. It will run the request as soon as the page loaded. And I will run a function as soon as it finish getting the data from the 2 ports. But so far, only can get the data from local port 1000. I have check the ports already but no problem. The problem must have been the javascript.
js:
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:1000/data1";
var info1;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
info1 = jQuery.parseJSON(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
var xmlhttp1 = new XMLHttpRequest();
var url1 = "http://localhost:2000/data2";
var info2;
xmlhttp1.onreadystatechange = function () {
if (xmlhttp1.readyState == 4 && xmlhttp1.status == 200) {
info2 = jQuery.parseJSON(xmlhttp1.responseText);
reload(info1, info2);
}
}
xmlhttp1.open("GET", url1, true);
xmlhttp1.send();
function reload(info1, info2) {
alert("success");
// processing the data
}
Is it that something wrong with the javascript?

JSON parse error: Cannot read property

I have created some little jt code, but it gives me error
function Mind(){
var request = "request";
var reply = "reply";
var words = '';
this.Reply = function(){
if(request == words.nouns[0].noun){
reply = words.nouns[0].noun;
}
else
reply = this.words.nouns[0].noun;
}
this.SetRequest = function(req){
request = req;
}
this.GetReply = function(){
return reply;
}
this.Parse = function(u){
var xmlhttp = new XMLHttpRequest();
var url = u;
var result;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
words = JSON.parse(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
return result;
}
this.Construct = function(){
words = this.Parse('mind/words.json');
}}
var mind = new Mind();
mind.Parse('mind/words.json');
and here is my json file
{
"nouns": [
{"noun": "child"},
{"noun": "father"}
]
}
In command live all goes well, but when I run this code, appears error
Uncaught TypeError: Cannot read property 'nouns' of undefined
Mutliple errors. The most fundamental one is that your code ignores that XMLHttpRequest is async, and wont return a value in the same way as "regular" functions. Read about it here: How to make a function wait until a callback has been called using node.js. The TL;DR is that you have to pass in a "callback-function" to your parse-method and "return" your value using that function, instead of using a return-statement. Google for "javascript callbacks" and read a few tutorials if this concept is new to you!
You also have some minor errors, like returning result from Parse, but never actually setting result to anything. Also words is being assigned in multiple places in a way that doesn't really make sense. But both of these things will go away when you solve the sync/async issues.
EDIT:
Essentially the fix looks like this:
this.Parse = function(u, callback){ // this "callback" is new
var xmlhttp = new XMLHttpRequest();
var url = u;
var result;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
words = JSON.parse(xmlhttp.responseText);
callback(null, words); // we're "returning" the words here
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
// no return statement here!
}
this.Construct = function(){
this.Parse('mind/words.json', function(error, words) {
// here you can use your words!
});
}}

Calling a XMLHttpRequest continuously

At the moment I am calling a function on a setInterval basis.
This function makes a XMLHttpRequest to my server to get update info. If there is an update available I update an image (using canvas element).
Is this the optimum way to do this sort of thing?
My code:
Calling code:
function StartFeedUp() {
if (tmrStartFeedUp) window.clearInterval(tmrStartFeedUp);
tmrStartFeedUp = setInterval(GetNextImage, 330);
}
My called function:
var isProcess = false;
function GetNextImage() {
try {
if (!isProcess) {
isProcess = true;
var urlTS = '/Cloud/isNewFrames.ashx?alias=' + alias + '&version=' + version + '&guidlogon=' + guidlogon;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", urlTS, true);
xmlhttp.timeout = 200;
xmlhttp.send();
var nextts = xmlhttp.responseText;
}
isProcess = false;
}
catch (err) {
isProcess = false;
document.getElementById("divMode2").innerHTML = err;
}
}
Other than repeating the XHR call, you can use HTML5 Web Sockets which allows you to maintain a connection to the server, whereby the server would push data as and when needed. Web Sockets are relatively new and so aren't supported by old browsers.
Your XHR is asyncronous so you should be listening on the onreadystatechange event instead of always expecting the response to be available directly after the send() call:
xmlhttp.open("GET", urlTS, true);
xmlhttp.timeout = 200;
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
console.log("received " + xmlhttp.responseText);
}
}
xmlhttp.send();

Categories