is there a race condition in this javascript? - javascript

In the following js snippet
request = new XMLHttpRequest
request.open('GET', '/my/url', true)
request.send()
request.onload = function() {
data = JSON.parse(this.response)
}
should the assignment of the on load be before the send() to avoid a race condition. Or does the browser deal with it for you (by firing the on load when you get round to assigning it).

Your request should look more like:
var request = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP');
request.open('GET', '/my/url');
request.onreadystatechange = function(){
if(request.readyState == 4 && request.status == 200){
console.log(request.responseText);
}
}
request.send();
To further answer your question request.send() should happen last, because if the response comes back before the function is assigned to request.onreadystatechange, there could be a problem, although it's very unlikely that the response would be that fast.

Related

Execute a http request response in javascript

I have an http request which delivers 'JSON.stringify(data)'.
var xhr = new XMLHttpRequest();
xhr.open("GET", "/api/hello", true);
xhr.send();
xhr.onreadystatechange = function () {
console.log(xhr.responseText);
};
How can I run the code and print the contents of data?
your code should be working, the endpoint may be the problem, check the url your trying to get into the endpoint from, then don't forget to check the readyState and the status of your request before doing nothing.
xhr.onreadystatechange = function () {
if (xhr.readState === 4 && xhr.status === 200)
{
console.log(xhr.responseText);
}
};

Parsing JSON url in pure javascript

I'm trying to parse a url in pure javascript, just one executable file.
url = 'http://myurl.php?format=json'
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var mystuff = JSON.parse(request.responseText);
} else {
// some error
}
};
request.onerror = function() {
// some error
};
request.send();
console.log(mystuff);
When I do this, I get a XMLHttpRequest is not defined error. What's the best way to do this, the simplest way?
Thank you.
This statement is wrong you should url as a variable not "url" as a string,
request.open('GET', 'url', true);
to
request.open('GET', url, true);
Furthermore the xmlHttpRequest works only on some versions of browsers.
You could do something like this to check whether xmlhttpRequest works on your browser,
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}

onreadystatechange only firing once

I have the following code for my request:
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) // state of 4 is 'done'. The request has completed
{
callback(req.responseText); // The .responseText property of the request object
} else { // contains the Text returned from the request.
console.log(req.readyState);
}
};
req.open("GET", url, true);
req.send();
However, the readyState is changing to 1 and firing correctly (I'm seeing it echoed in the console) but it simply won't progress to 2. After awhile it times out and I get this in the console:
Failed to load resource: net::ERR_CONNECTION_TIMED_OUT
Uncaught SyntaxError: Unexpected end of input
Anyone have any idea why this might be?
Put this
req.open("GET", url, true);
req.send();
above this line
req.onreadystatechange = function() {
Sorry all, this ended up being a VPN issue, not a scripting one.
function getLatestfileinAllPath(urls)?
{
for(i = 0;i<urls.length;i++){
run(i)
}
function run(){
var request = new XMLHttpRequest();
request.open('POST', url[i]);
request.send(JSON.stringify({"data":"some data"}));
request.onreadystatechange = function()
{
if (request.readyState === XMLHttpRequest.DONE && request.status == 200)
{
console.log(JSON.parse(request.response));
}
}
};
}
}

A partial build of jQuery just for $.ajax (XMLHttpRequest) functionality?

Is there a way to obtain or compile a stripped down version of jQuery, that just contains the $.ajax function, and anything that it depends on?
NOTE:
Background: Wish to create a script which includes just this function in-lined within my own (with proper attributions of course)
Including the entire jQuery would be overkill for my requirements
A great example of what I am looking for is Modernizr:
http://modernizr.com/download/
The download page allows you to select which parts you want, and it will work out the dependencies, and give your a partial build, containing just what you have asked for.
Why do you even need jQuery?
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onreadystatechange = function() {
if (this.readyState === 4){
if (this.status >= 200 && this.status < 400){
// Success! run your success function
resp = this.responseText;
} else {
// Error :( run your error function
}
}
};
request.send();
request = null;
Or a POST:
var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onreadystatechange = function() {
if (this.readyState === 4){
if (this.status >= 200 && this.status < 400){
// Success! run your success function
resp = this.responseText;
} else {
// Error :( run your error function
}
}
};
request.send(data);
request = null;
Taken from here, a fantastic resource for Vanilla JS alternatives to jQuery. This should work with IE8+.

"XMLHttpRequest Exception 101" on nested AJAX queries

I'm doing an AJAX fetch of a binary file the I am parsing in javascript. (Quake 2 BSPs, if anyone cares.) The code to fetch and parse the initial file is working fine, and looks roughly like this:
function loadFile(url) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
var parsed = parseFile(request.responseText);
}
};
request.open('GET', url, true);
request.overrideMimeType('text/plain; charset=x-user-defined');
request.setRequestHeader('Content-Type', 'text/plain');
request.send(null);
}
As I said, that works fine, and everything loads and parses correctly. However, the file also describes several secondary files (textures) that need to be retrieved as well, and so I've added an inner loop that should load and parse all of those files, like so:
function loadFile(url) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
var parsed = parseFile(request.responseText);
for(var i = 0; i < parsed.files.length; ++i) {
loadSecondaryFile(parsed.files[i].url); // Request code here is identical to this function
}
}
};
request.open('GET', url, true);
request.overrideMimeType('text/plain; charset=x-user-defined');
request.setRequestHeader('Content-Type', 'text/plain');
request.send(null);
}
function loadSecondaryFile(url) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
var parsed = parseSecondaryFile(request.responseText);
}
};
request.open('GET', url, true);
request.overrideMimeType('text/plain; charset=x-user-defined');
request.setRequestHeader('Content-Type', 'text/plain');
request.send(null);
}
But every request made from within that loop immediately fails with the message (in Chrome, Dev Channel): NETWORK_ERR: XMLHttpRequest Exception 101 This strikes me as strange, since if I call loadSecondaryFile outside of loadFile it works perfectly.
My initial impression was that initiating an one ajax call in the onreadystatechage of another may be bad juju, but wrapping the secondary ajax calls in a setTimer doesn't make any difference.
Any ideas?
And... SUCCESS! So I feel really stupid, and I realize now that there's no way anyone else could have given me a solution with the information I presented. Terribly sorry!
It has nothing to do with AJAX and everything to do with how I was getting my URLs. Recall that I mentioned I was loading binary data from a Quake2 bsp, in this case, texture paths. Textures in the bsp format are stored as fixed length 32 bit strings with null padding. I was reading them using substr like so:
var path = fileBuffer.substr(fileOffset, 32);
Which I thought was giving me a string like "e2u3/clip", but in reality was giving me "e2u3/clip\0\0\0\0..." Of course, when printed this would look correct (since console.log represents the null char as nothing.) but the browser recognized it immediately as a bad URL and tossed it out.
Changing my read code to:
var path = fileBuffer.substr(fileOffset, 32).replace(/\0+$/,'');
Gives me valid strings and fixes all of my apparent AJAX problems! sigh
Thanks for all the suggestions! It helped put me on the right track.

Categories