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+.
Related
I'm creating a website to progress in javascript and I have a little problem, every ways I try, my browser doesn't want to load my json file.
I tried many codes i found on internet but none of them work (or I don't know how to make them work). Finally i fond this one which is quite easy to understand but yhis one too doesn't work and always return an error message.
function loadJSON(path,success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 1) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path , true);
xhr.send();
}
function test()
{
loadJSON('test.json', function(data) { console.log(data); }, function(xhr) { console.error(xhr); });
}
I run the test function but everytimes, the console return me an error. Someone have an idea to solve my problem ?
status is the HTTP response code.
200 means the request has been successful. The status will most likely never be 1.
Here is a list of HTTP codes
As a solution, I suggest using the fetch API, which is the modern way to query files.
Here are some examples on how to use it
If you really want to use AJAX, use this :
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var resp = this.response;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
Source : You Might Not Need jQuery
I am making an api call to
http(s)://{hostaddress:port}/com.broadsoft.xsi-actions/v2.0/user/{userid}/services/callcenter
I have changed the appropriate information in the URL to reflect the correct host address/port / user id.
When that is complete, the page requests that I log on with a Username and Password.
I can manually enter this information, and receive the XML that I need. This is not Ideal. I would rather have a form that passess in this information.
To my understanding, this information is passed within the "headers". I have tried to look up how to do this, and even attempted using postman without much luck. I am not sure how to do this.
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "http(s)://{hostaddress:port}/com.broadsoft.xsi-actions/v2.0/user/{userid}/services/callcenter", true);
xhttp.send();
}
per w3 schools I can use setRequestHeader() which adds a label/value pair to the header to be sent.
I have tried
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "http(s)://{hostaddress:port}/com.broadsoft.xsi-actions/v2.0/user/{userid}/services/callcenter", true);
xhttp.send();setRequestHeader(Username:myUserName,Password:myPassword);
}
with no resolution. once i get this working i will set up the form and pass in the values.
You are using setRequestHeader in the wrong way and calling send before setting headers in any case.
Try with
xhttp.setRequestHeader('Username', myUserName);
xhttp.setRequestHeader('Password', myPassword);
xhttp.send(); // only call send after setting up the headers
xhttp.setRequestHeaders(name, value) and it should be invoked before xhttp.send(). mdn
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));
}
}
};
}
}
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.
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.