Not able to load data from xml in plain javascript - javascript

I am trying to load my data from xml. Here is my code
function myFunction(){
debugger;
var url = "js/MyXml.xml";
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', url, true);
httpRequest.send();
var xmlDoc=httpRequest.responseXML;
}
Here in httpRequest i am getting status code is and httpRequest.responseXML = null
Cab you please help me what I am doing wrong.

In your case, you have used XMLHttpRequest call, that was Asynchronous. Also, you tried to assign the return value to your variable before the actual answer arrived, whether it was reading a file or actual response from the server.
In any case, if you decide to use Async (which is preferred way), then please observe the code provided below.
Also, I encourage you to do more investigation on your own, in the links provided below.
var url = "js/MyXml.xml";
var xhttp = new XMLHttpRequest();
var xmlDoc = null;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
xmlDoc = httpRequest.responseXML;
}
};
xhttp.open("GET", url, true);
xhttp.send();
In addition to, you could also a fetch, which should be available in your javascript environment as well. According to MDN, this is still experimental technology, but it will provide beneficial knowledge.
And lastly, for the task at hand you could use a library, that is designed to make this task easier then native XMLHttpRequest. One of them is a jQuery. It could be easier to use it.
You can find more information here. Also easy to follow SO question.

Change it to that:
httpRequest.open('GET', url, false);
With the true parameter you're setting the request to be asynchronous.
Which means that you reading the response before the request finished executing.
Setting the last parameter to false will set the request to be synchronous so it will block your web page until the request finishes.
A proper way of doing it is creating an event on when the asynchronous request finishes.
Here is an example:
function myFunction() {
debugger;
var url = "js/MyXml.xml";
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', url, true);
httpRequest.onload = function(oEvent) {
var xmlDoc = httpRequest.responseXML;
//Continue code here
}
httpRequest.send();
}

Related

Link triggering XMLHttpRequest

I have made a simple XMLHttpRequest which does work, it sends request etc. Just like in W3 schools.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demox").innerHTML = this.responseText;
}
};
xhttp.open("POST", "textx.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=" + textxx);
}
The problem starts when I try to trigger the request by clicking a link, which sends me to the php file which processes the request. I find it hard to understand on my current level why it doesn't work, since it worked with simple forms and such.
I get:
"Notice: Undefined index: fname ..."
So, I assume, it means the variable wasn't sent. Can someone explain? Or is there way to debug the things that are being sent from one page to another. All I found was a debugger in chrome which indeed captures the requests, but has no real use, since I get sent to the textx.php page and all is lost.
Not really sure, where your problem might be, maybe try:
var xhttp = new XMLHttpRequest();
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.open("POST", "textx.php", true);
xhttp.onreadystatechange = function() {
if (this.readyState === 4){
if(this.status===200 || this.status===0){
document.getElementById("demox").innerHTML = this.responseText;
}
};
var fname = "fname=" + textxx;
xhttp.send(fname);
}
You might console.log(xhttp); and see the step by step profile and find out where the problem might be.
Either way, I am still not sure, but I uploaded my page(code) to a hosting server and the code worked. PHP didn't show any warnings and all went as planned. The problem it seems has to do something with running a local server(WAMP). Changing PHP version didn't help. I may need to dig a little deeper on this.

Detect all XMLHttpRequest calls are completed

I have Javascript code that uploads files to a server. Each upload is done using a XMLHttpRequest object.
xhr = new XMLHttpRequest();
//...
xhr.open('POST', 'https://<bucket>.s3.amazonaws.com/', true);
xhr.send(fd);
The upload in parallel works fine. The problem is that I need to detect when all of them have finished, because I have to do a final submit, but only if all the uploads are completed.
My first try was save all the xhr objects in an array but I didn't know what to do with that :-(
var arrayxhr = [];
//...
//A loop {
xhr = new XMLHttpRequest();
arrayxhr.push(xhr);
xhr.open('POST', 'https://<bucket>.s3.amazonaws.com/', true);
xhr.send(fd);
//}
//And now?
I found this jQuery function https://api.jquery.com/ajaxcomplete/, but the same, I don't really know how to use it.
Can you help me please?
TIA,
If you can use jQuery you can use jQuery AJAX Deferred interface/methods and $.when method. $.ajax/$.post/$.get and other jQuery AJAX methods always return jQuery Deferred object:
$.when($.get('someUrl'), $.get('anotherUrl')).then(function () {
//all request complete
});
In native javascript you can use native Promise or any promise library:
http://www.javascriptoo.com/rsvp-js
http://www.javascriptoo.com/Q (example https://gist.github.com/matthewp/3099268)
Also good article about Promises - http://www.html5rocks.com/en/tutorials/es6/promises/.
Native Promise with XMLHttpRequest example:
function doAjaxRequest(method, url, data){
var promise = new Promise();
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
// Register the event handler
xhr.onload = function(){
if(xhr.status === 200){
promise.resolve("Done");
} else{
promise.reject("Failed");
}
};
data = data || {};
xhr.send(data);
return promise;
}
Promise.all(doAjaxRequest('post', 'someUrl'), doAjaxRequest('post', 'anotherUrl')).then(function (values) {
//all request complete
});
Well, this is not exactly the answer to my question (detect that the asynchronous calls are completed), but this answer works for me. I copy here just in case it helps someone else:
2: On the client-side, create a stack of files to upload and upload
one at a time, calling the next one on the "Complete" callback of the
previous.
https://stackoverflow.com/a/15557631/1893936

Pass the value of an xhr onload function globally

In an app I'm creating I have the below XMLHttpRequest and I'm trying to pass the results of data inside the xhr.onload() into an array that's created within the same parent function.
var url = 'http://api.soundcloud.com/resolve.json?'+resource+'&'+CLIENT_ID;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function(){
var data = JSON.parse(xhr.responseText);
console.log(data.permalink_url);
};
xhr.send();
Below this I have the building blocks of an array and I'm trying to pass the results of data into the track string.
var metadata = {
id: val,
title: title,
url: posturl,
track: data.permalink_url
};
Everything I've tried thus far either returns undefined or function and now I'm totally out of ideas...
Ajax executes asynchronously (generally). This is vital to how Ajax works. What this means is that you can't count on the when the onload method will fire, or even if it will fire. What this means is that all code that depends on the xhr.responseText (result of the HTTP request) has to be done within the callback itself. For example:
xhr.onload = function () {
// This will execute second
doStuffWithData(JSON.parse(xhr.responseText));
}
// This will execute first
xhr.send();
var anything = anythingElse;
Like I said in the comment to my previous answer, you can change the one line to xhr.open('GET', url, false). It will make the request synchronous and will prevent everything else from running until the request completes. It will allow you to access xhr.responseText without waiting for an onload function.
CLIENT_ID = 'client_id=xxx';
var src = track,
match = src.match(/url=([^&]*)/),
resource = match[0],
stream = decodeURIComponent(match[1]) + '/stream/?' + '&' + CLIENT_ID;
var url = 'http://api.soundcloud.com/resolve.json?' + resource + '&' + CLIENT_ID;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send();
parsedResults.push({
title: title,
track: JSON.parse(xhr.responseText)
});
You can see it in action here. It appears to be broken in Chrome for some reason. Works in Firefox though. I assume it's something to do with the CORS + 302 redirect + synchronous request.
I've gone for Explosion Pills solution. The only problem I encounter is that the links that get crawled don't always come back in the same order each time I run the node app. Realistically they should return in the order that they're crawled in (which would be newest posts first, right?) However this isn't always the case?

How to add callback to AJAX variable assignment

I've got a variable responce which is assigned via an AJAX function send(). When I make the assignment...
responce = send();
response returns before send does giving me back an undefined how can I add a callback to prevent this from happening?
EDIT: a clarification on what I'm asking..
It's still returning undefined. I'm assigning the variable with the function send send returns onreadystatechange however when my code is executing.. response returns as undefined before send() can return. How do I stop the code under response from running on till response has been assigned sends value?
EDIT2:
The following code is my send function...
function send(uri)
{
var xhr = new XMLHttpRequest();
xhr.open("POST",uri,true);
xhr.onreadystatechange = function (send){
if(xhr.readyState == 4){
return xhr.responseText;
}
}
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
xhr.send(null);
}
You are using Ajax in a asynchronous manner, but you are treating it to be synchronous.
Asynchronous calls goes off to do its job while the rest of the code after the initial send call executes. You are getting undefined because the code is not returning anything.
If you look at the XMLHttpRequest object, the 3rd argument in the open method is the asynchronous flag.
open("method", "URL"[, asyncFlag[, "userName"[, "password"]]])
Setting it to true [default is left off] will make an asynchronous call. Setting it to false will make it synchronous.
The problem with using synchronous calls is it locks up the user's browser until the call is returned. That means animated gifs stuff, browser timers stop, and so on. If the server takes forever to respond, the user can not do anything.
The best solution is to avoid using synchronous calls. Use the call back to continue the code execution flow.
So based on your edit, I will edit my response with a basic solution
function send(uri, callback)
{
var xhr = new XMLHttpRequest();
xhr.open("POST",uri,true);
xhr.onreadystatechange = function (send){
if(xhr.readyState == 4){ //You really should check for status here because you can get 400, 500, etc
callback(xhr.responseText);
//return
}
}
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
xhr.send(null);
}
function myFunction(){
var myUrl = "foo.php";
//show a loading message or soemthing
var someDiv = document.getElementById("loadingMessage");
someDiv.style.display = "block";
//Second half of your function that handles what you returned.
function gotData( value ){
someDiv.style.display = "none";
alert(value);
}
send(myUrl, gotData);
}
If you really want to do synchronous and you do not mind locking up a user's browser
function send(uri, callback)
{
var xhr = new XMLHttpRequest();
xhr.open("POST",uri,false);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
xhr.send(null);
if(xhr.status==200){
return xhr.responseText;
}
else{
return null;
}
}
I presume you are talking about the XMLHTTPRequest.send() method, rather than a framework's wrapper.
send does not return anything. It will always return undefined.
To get the HTTP response, you need to monitor onreadystatechange, as countless StackOverflow answers and internet tutorials (e.g. this one) demonstrate.
you must assign the value to your response on readystatechange event of your request, something like this:
req.onreadystatechange = function(){
if (req.readyState===4) { // checks if data is already loaded.
callback(req.responseText,req.status); //call your callback function with response and status as parameters.
}
};
try this:
function send(uri, callback)
{
var xhr = new XMLHttpRequest();
xhr.open("POST",uri,true);
xhr.onreadystatechange = function (send){
if(xhr.readyState == 4 and callback){
callback();
}
}
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
xhr.send(null);
}
send("uri here", function(){
//whatever needs to be done after request
})

XMLHTTPrequest request not working

I tried the following code to send request to jsp page on a click of button. I checked on Httpfox but no request is going. I just used the whole of this code in the body of the html code. Am I doing some silly mistake. Kindly suggest..
<button type="button" onClick="handleButtonClick();">Click Me!</button>
<script type="text/javascript">
function handleButtonClick()
{
// Declare the variables we'll be using
var xmlHttp, handleRequestStateChange;
// Define the function to be called when our AJAX request's state changes:
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var substring=xmlHttp.responseText;
// Do something with the text here
alert(substring);
}
}
xmlhttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://csce:8080/test/index.jsp?id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
</script>
Well, in JavaScript, variables are case-sensitive. You have xmlHttp and xmlhttp; those should be the same.
You've also got <pre><code> at the beginning of your <script> block, which is a JavaScript syntax error.
Since no request is being made, I am not convinced you can actually make requests to "http://csce:8080" as FireFox may not see that URL as being on the same subdomain (You cannot make Ajax requests for resources not on the same domain as the requestor).
Suppose you made the URL relative. Is a request even generated then? If so, that is likely your problem.
Quote: xmlhttp = new XMLHttpRequest();
Two things. First, you might want to use a more robust method of getting an XMLHttpRequest object. Second, javascript is case-sensitive; xmlhttp != xmlHttp
xmlHttp = (function (x,y,i) {
if (x) return new x();
for (i=0; i<y.length; y++) try {
return new ActiveXObject(y[i]);
} catch (e) {}
})(
window.XMLHttpRequest,
['Msxml2.XMLHTTP','Microsoft.XMLHTTP']
);
Quote: http://csce:8080/test/ind...
Keep in mind that cross-domain xmlhttp is verboten. Unless you're serving from csce:8080, that ain't gonna work.

Categories

Resources