Doing multiple XMLHttpRequest from different url - javascript

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?

Related

How to get a certain line from xml from other webpage (url) in js?

const xhrRequest = new XMLHttpRequest();
xhrRequest.onload = function()
{
dump(xhrRequest.responseXML.documentElement.nodeName);
console.log(xhrRequest.responseXML.documentElement.nodeName);
}
xhrRequest.open("GET", "/website_url.xml")
xhrRequest.responseType = "document";
xhrRequest.send();
I'm trying to request a xml page from a page, but i'm unable to get certain line from xml in javascript. Thank you!
You can easily send requests to other pages with an AJAX http request found here: https://www.w3schools.com/js/js_ajax_intro.asp
Here is an example function:
function SendRequest(){
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
// Success
}
};
xmlhttp.open("GET", "example.com", true);
xmlhttp.send();
}
Now, about getting a value from the xml document, you can use .getElementsByTagName(). Notice that this is an array of elements so you have to append an index such as [0]
This would go inside the onreadystatechange of the http request
if(this.readyState == 4 && this.status == 200){
let xmlDocument = this.responseXML;
console.log(xmlDocument.getElementsByTagName("TestTag")[0].childNodes[0].nodeValue);
}
So if the xml document had an element like:
<TestTag>Hello</TestTag>
the function would print Hello

javascript - function with setInterval not starting immediately on page load

I have this code that continuously accesses a url at given intervals:
window.setInterval(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var valr5 = JSON.parse(this.responseText);
document.getElementById("wind").innerHTML = valr5.wind;
}
};
xmlhttp.open("GET", "sample.com/", true);
xmlhttp.send();
}, 30000);}
My problem is that the script would run after 30s, as set in the code. So the page is blank for 30s.
What I want to happen is on page load, the script will run so I won't see I blank page, and from that, access the URL every 30s or so.
How can I do this? thanks.
Save the function in a variable first, call the function, then call setInterval with it:
const updateWind = () => {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var valr5 = JSON.parse(this.responseText);
document.getElementById("wind").innerHTML = valr5.wind;
}
};
xmlhttp.open("GET", "sample.com/", true);
xmlhttp.send();
};
updateWind();
window.setInterval(updateWind, 30000);

Javascript not returning AJAX data (JSON, PHP, AJAX) [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I've got two functions in Javascript. One gets JSON data from a php file.
{"company_name":"","job_title":"Superhero","unix_time_convert":"Posted 06th of September '18","link":"2"}
The javascript function to return the JSON is this:
function assignJsonData() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = (this.response);
return data;
//alert( data );
}
};
xmlhttp.open("GET", 'test_echo.php?row=1', true);
xmlhttp.send();
}
Notice that alert( data ); will return the JSON data in a box.
But when I assign the function to a variable elsewhere like so, it returns undefined.
window.onload = function () {
var data = assignJsonData();
alert(data);
}
What am I missing here?
Sorry to ask, I've been on this for hours...
Thanks
Andy
You should use callBack to retrieve data from ajax request , and get data when ajax request is finieshed , your could should look like :
function assignJsonData(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback(this.response);
}
};
xmlhttp.open("GET", 'test_echo.php?row=1', true);
xmlhttp.send();
}
window.onload = function () {
assignJsonData(function(data){
alert(data);
});
}
As Jafar pointed, you should use a callback!
If you want to check the order the things is executed, run the code bellow.
var returnData = "";
function assignJsonData() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(this.readyState, this.status);
if (this.readyState == 4 && this.status == 200) {
returnData = this.response;
console.log('enter');
//console.log(this.response);
//return data;
//alert( data );
}
};
xmlhttp.open("GET", 'https://jsonplaceholder.typicode.com/todos/1', true);
xmlhttp.send();
}
assignJsonData();
console.log("returnData: " + returnData);
XMLHttpRequest is asynchronous. You need to either use a callback or a Promise.
function assignJsonData(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = this.response
callback(data)
}
};
xmlhttp.open("GET", 'test_echo.php?row=1', true);
xmlhttp.send();
}
window.onload = function () {
assignJsonData(function(data) {
alert(data)
});
}
You need to use Promise.
Check - How do I promisify native XHR?
You don't have the data in alert, because the response is not ready I guess.

Return WebMethod Response & Use If Statement To Alert User Based On Response

I'm trying to include an if statement that analyzes the webmethod response which is either true or false. I just want to alert the user the post was successful if the response is true or the post was not successful if the response is false.
I can get the response using xhttp.responseText but I can't figure out how to build that into an if statement inside my javascript below:
//JavaScript that Posts to WebMethod
<script>
function createNewComment() {
var xhttp = new XMLHttpRequest();
var url = "http://localhost:57766/PALWebService.asmx/insertComment"
var a = document.getElementsByName("existingguid")[0].value;
var b = document.getElementsByName("newcomment")[0].value;
var c = 'existingguid=' + a + '&newcomment=' + b;
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
}
};
xhttp.send(c);
}
</script>
I figured it out. After checking that readyState was 4 and status was 200 I simply nested another if statement to check the responseText from the XMLHttpRequest and it was true I called another function and if it was false I notified user the post failed on the webmethod. It may not be perfect, but it works for what I need.
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
if (xhttp.responseText = true) {
addComment(b, today, userName);
}
else {
document.getElementsByName("newcomment")[0].value = '';
$("#commentLabel").html("Your comment was not saved in the database. Please try again or contact system admin.");
}
}
};

Asynchronous request in react-native

I use this piece of code to asynchronously make a request with React-Native, but it seems like it doesn't get it. The request has been tested separately and the data should be valid.
var data = [{name: 'simon'}];
const req = new XMLHttpRequest();
req.open('GET', testedValidUrl, true);
req.send();
req.onreadystatechange = processRequest;
var name ="";
function processRequest(e) {
if(req.readyState == 4 && req.status == 200){
var response = JSON.parse(req.responseText);
data[0].name = response.name;
}
// setTimeout(()=>{},1000);
}
I thought that maybe it was because of concurrence and that the large array in the real application takes less time to construct than to get the data from the server. Adding setTimeout() did not fix it.
var data = [{name: 'simon'}];
const req = new XMLHttpRequest();
function processRequest(e) {
if(req.readyState == 4 && req.status == 200){
var response = JSON.parse(req.responseText);
data[0].name = response.name;
}
req.onreadystatechange = processRequest;
req.open('GET', testedValidUrl, true);
req.send();
var name ="";
If you set the event handler, (onreadystatechange) after you send/open the request, the readyState has already changed and thus it won't be called.

Categories