I am using AJAX and i have four URLS of HTML. I want to fetch this four urls using AJAX and want to load them in four different divs dynamically. Although i have written code to access one url. Code is here...
function load(url)
{
if (window.XMLHttpRequest) {
try {
req = new XMLHttpRequest();
} catch (e) {req = false;}
} else if (window.ActiveXObject) {
// For Internet Explorer on Windows
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
req = false;
}
}
}
if(req) {
req.open('GET', url, false);
req.send(null);
}
}
load('<%=request.getScheme()%>://${domain}/car-rental/html/global/${siteLanguage}/terms/PrefMbrGlobalTermsMiddle-text.html');
function display(id)
{
var element = document.getElementById(id);
if (element && req)
{
// Synchronous request, wait till we have it all
element.innerHTML = req.responseText;
}
}
I want to do same type of logic to load four urls .. Please help me out...
What I understood from your code is load function you are using to make an ajax call. So what can do call load function as:
load("url1","target-div1");
load("url2","target-div2");
load("url3","target-div3");
load("url4","target-div4");
inside load on successful of AJAX set the content target-div with AJAX response.
Related
I have several URL similar to https://zkillboard.com/api/stats/solarSystemID/31000007/
I am trying to extract the JSON from the url into an object.
I have been able to get as far as this which returns a Promise, PromiseState: fulfilled and PromiseResults contains an object with the data I am looking for.
async function readJSON(url:string) {
var request = new XMLHttpRequest();
request.open ('get', url, false)
request.send(null)
if (request.status == 200) {
return JSON.parse(request.responseText)
}
}
const systemJSON = readJSON('https://zkillboard.com/api/stats/solarSystemID/31000007/')
console.log(systemJSON)
How can I ensure that my console.log only returns the PromiseResult?
This seems to have fixed it for me, removed the async from the function as well as .responseText in the JSON.parse()
function readJSON(url:string) {
var request = new XMLHttpRequest();
request.open ('get', url, false)
request.send(null)
if (request.status == 200) {
return JSON.parse(request.response)
}
}
const systemJSON = readJSON('https://zkillboard.com/api/stats/solarSystemID/31000007/')
const printJSON = () =>{
console.log(systemJSON)
}
printJSON();
First off, when handling json from an external source I would suggest wrapping it in a try/catch function, to avoid unsuspecting errors.
Secondly I think the issue is that readJSON returns a promise, so you might need to await it.
try {
const json = await readJSON('https://zkillboard.com/api/stats/solarSystemID/31000007/')
const systemJSON = JSON.parse(json);
} catch (error) {
// Woops something happend - see error variable
}
I am creating a website that reads externally hosted json files and then uses node.js to populate the sites content.
Just to demonstrate what I'm after, this is a really simplified version of what I'm trying to do in node.js
var ids = [111, 222, 333];
ids.forEach(function(id){
var json = getJSONsomehow('http://www.website.com/'+id+'.json');
buildPageContent(json);
});
Is what I want to do possible?
(Marked as a duplicate of "How do I return the response from an asynchronous call?" see my comment below for my rebuttal)
You are trying to get it synchronously. What you should aim for instead, is not a function used like this:
var json = getJSONsomehow('http://www.website.com/'+id+'.json');
but more like this:
getJSONsomehow('http://www.website.com/'+id+'.json', function (err, json) {
if (err) {
// error
} else {
// your json can be used here
}
});
or like this:
getJSONsomehow('http://www.website.com/'+id+'.json')
.then(function (json) {
// you can use your json here
})
.catch(function (err) {
// error
});
You can use the request module to get your data with something like this:
var request = require('request');
var url = 'http://www.website.com/'+id+'.json';
request.get({url: url, json: true}, (err, res, data) => {
if (err) {
// handle error
} else if (res.statusCode === 200) {
// you can use data here - already parsed as json
} else {
// response other than 200 OK
}
});
For a working example see this answer.
For more info see: https://www.npmjs.com/package/request
I think problem is in async request. Function will return result before request finished.
AJAX_req.open( "GET", url, true );
Third parameter specified async request.
You should add handler and do all you want after request finished.
For example:
function AJAX_JSON_Req( url ) {
var AJAX_req = new XMLHttpRequest.XMLHttpRequest();
AJAX_req.open( "GET", url, true );
AJAX_req.setRequestHeader("Content-type", "application/json");
AJAX_req.onreadystatechange = function() {
if (AJAX_req.readyState == 4 && AJAX_req.status == 200) {
console.log(AJAX_req.responseText);
}
};
}
I need to display hello world using servlet program in browser by Ajax call but on clicking button I am not to display it what could be reason of this error:
Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file:///D:/workspace/Poc_Ajax/WebContent/WEB-INF/HelloWorld'.
<!DOCTYPE html>
<html>
<head>
<script>
function getXMLHttpRequest() {
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
/*
* AJAX call starts with this function
*/
function makeRequest() {
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("POST", "HelloWorld", true);
xmlHttpRequest.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
xmlHttpRequest.send();
}
/*
* Returns a function that waits for the state change in XMLHttpRequest
*/
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned
// it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
document.getElementById("hello").innerHTML = xmlHttpRequest.responseText;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
</script>
</head>
<body>
<div>Getting Started with AJAX using JAVA: Hello World!</div>
<div id="hello"><button type="button" onclick="makeRequest()">Say Hello!</button></div>
</body>
</html>
To run a servlet program you need to make an HTTP request to a web server that is configured to execute the servlet.
Your Ajax URL (as displayed in the error message) starts with file:// so you are trying to deal with a local file instead of a webserver.
Install a webserver (such as Tomcat). Load your HTML document from it. Make sure that "HelloWorld" is a relative URI from that HTML document to the servlet URL.
I have the following code. The async call never returns anything. Even for google.com.
try
{
using (
var client = new HttpClient()) {
var response = client.GetAsync("http://www.google.com");
Debug.WriteLine("Coming here1"+response.Result.IsSuccessStatusCode);
if (response.Result.IsSuccessStatusCode)
{
// by calling .Result you are performing a synchronous call
Debug.WriteLine("Coming here1");
var responseContent = response.Result.Content;
// by calling .Result you are synchronously reading the result
string responseString = responseContent.ReadAsStringAsync().Result;
//Console.WriteLine(responseString);
}
else { Debug.WriteLine("else"); }
}
}
catch(Exception e)
{
Debug.WriteLine(e.ToString());
}
}
Try This
try{
WebClient wc = new WebClient();
wc.DownloadStringCompleted+= (sender,args) => {
Debug.WriteLine(args.results);
};
wc.DownloadStringAsync(new Uri(#"http://www.Google.com",UriKind.RelativeOrAbsolute));
}
catch(Exception e){ Debug.WriteLine(e.Message); }
You don't appear to be awaiting your Async call.
Try changing var response = client.GetAsync("http://www.google.com"); to var response = await client.GetAsync("http://www.google.com");
Remember to mark your method as async.
you're also blocking on your async call ReadAsStringAsync().Result. As with client.GetAsync, make sure to await the call instead of blocking with Result. This blog post speaks a bit on the topic.
Read up a bit on async/await. You'll love it once you get the hang of it.
Hi I know this is a bit wired, but right now my project has gone a bit mad. We have a RESTful application which can provide a bunch of services, we all know that DELETE is a verb to use to delete stuff. However, as we also know that HTML form cannot produce DELETE am I right? How do we solve this issue? And suggestion would be greatly appreciated.
Thanks,
You need to use javascript for that. Here is an example:
<script type="text/javascript">
function getXMLHttpRequest() {
try { return new XMLHttpRequest(); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
throw new Error("This browser does not support XMLHttpRequest.");
}
function sendDelete(url, confirmation, successUrl) {
if (confirm(confirmation)) {
var r = getXMLHttpRequest();
r.open("DELETE", url, false);
r.send();
if (r.status < 200 || r.status > 299) {
alert(r.responseText);
} else {
if (successUrl == null) {
location.reload(true);
} else {
location.href = successUrl;
}
}
}
}
</script>
Then you can just call the sendDelete() method from the onclick="" of your web page button.