Are there different styles of ajax? - javascript

I'm kind of new to using ajax but I've been largely successful. Most of my ajax calls look very similar to this:
function saveQueryProf(){
var currentDate = new Date();
var date=currentDate.getDate()+'/'+(currentDate.getMonth()+1)+'/'+currentDate.getFullYear();
$.ajax({
type: "POST",
url: "API.php",
data: { method: "createQueryProfile",
prof_name: $('#nameTxt').val(),
prof_SQL: $('#sqlTxt').val(),
date: date
},
datatype: "json"
}).done(function(returnresult) {
})
}
Using the $.ajax({ method. However, any time I see someone using "ajax" on youtube or other sites, their code looks more like this:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
I realize that these are doing different things, but what is the difference in these 2? And when I'm looking for answers online how could I find an answer that is more along the lines of the first style?

The first example, using $.ajax(), is specific to jQuery. It's a lot simpler than the built-in Javascript API, XMLHttpRequest. XMLHttpRequest doesn't require any external libraries to use, though it's more difficult. $.ajax() relies on XMLHttpRequest.

Your code requires the jQuery library to work (that's where $ and $.ajax come from). Their code is using XMLHttpRequest directly, which is built in to JavaScript, so it doesn't need any libraries. If you want your AJAX code to depend on jQuery, then just include it as a search term.

I saw that the question was already answered, but I think that more information can be added.
In your first example you are using jQuery ($.ajax call). You will need to add this library to your website in order to make it work. The easiest way is to add a tag with jQuery CND to your website.
The second example is using vanilla JavaScript, the XMLHttpRequest. It has more complex syntax (a strange mixture of upper and lowercase characters), but you don't need to add anything to the site. It will do the work, and once you are used to the syntax it might be all you need.
Third option that I have used for AJAX request is the fetch() method. Like XMLHttpRequest it is build in in the JavaScript language. fetch() has very simple syntax and allows easy use of promises. You might need promises if you will be making requests that will not return data immediately. Here's more information on fetch:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Fourth option that I've used for AJAX is Axios library. If you are including jQuery only for AJAX requests Axios is probably better choice. More read on Axios: https://github.com/axios/axios
If you want to dig a bit more on the differences and pros/cons between fetch() and XMLHttpRequest take a look on this thread:
Fetch API vs XMLHttpRequest

Shortly Ajax is an extension method which defined in JQuery for factory class XmlHttpRequest.

Related

Connect HTTP POST request to an onclick using JavaScript

I am trying to make an HTTP POST request using javascript and connecting it to an onclick event.
For example, if someone clicks on a button then make a HTTP POST request to http://www.example.com/?test=test1&test2=test2. It just needs to hit the url and can close the connection.
I've messed around in python and got this to work.
import urllib2
def hitURL():
urllib2.urlopen("http://www.example.com/?test=test1&test2=test2").close
hitURL()
I have read about some ways to make HTTP requests using JavaScript in this thread JavaScript post request like a form submit, but think it's overkill for what I need to do.
Is it possible to just say something like this:
<button onclick=POST(http://www.example.com/?test=test1&test2=test2)>hello</button>
Or build it in to an event listener.
I know that is not anything real but I am just looking for a simple solution that non-technical people can use, follow directions, and implement.
I honestly doubt there is something that simple out there but still any recommendations would be appreciated.
You need to use XMLHttpRequest (see MDN).
var xhr = new XMLHttpRequest();
xhr.open("POST", url, false);
xhr.onload = // something
document.getElementById("your_button's_ID").addEventListener("click",
function() {xhr.send(data)},
false
);
If you can include the JQuery library, then I'd suggest you look in to the jQuery .ajax() method (http://api.jquery.com/jQuery.ajax/):
$.ajax("http://www.example.com/", {
type: 'POST',
data: {
test: 'test1',
test2: 'test2'
}
})

Error : Ajax is Undefined

I am using the below code in a script tag to call one URL in the background.
var request = new Ajax.Request(logoffURL, {method : 'post'});
But I am getting script error Ajax is undefined.
Do I need to include any external scripts?
That code uses Prototype. If you want to use that code, you'll need to include Prototype into your page. For example, using Google's CDN:
<script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script>
Yes, you need to include some external script (jQuery, for instance) and learn how to do ajax calls there. There is no Ajax object in browser, but there is XMLHTTPRequest. But again - you must learn how to use it first. For instance - here is how you can use XMLHTTPRequest
Here's a good place to start:
http://api.jquery.com/jQuery.ajax/
As the example shows, you can do something like this:
$.ajax({
url: logoffURL,
context: document.body
}).done(function() {
alert("DONE");
});
I recommend using a CDN to reference jquery:
https://developers.google.com/speed/libraries/devguide#jquery

Reuse XMLHttpRequest object or create a new one?

I searched stackoverflow but got contradictory answers:
Why should I reuse XmlHttpRequest objects?
Ajax-intensive page: reuse the same XMLHttpRequest object or create new one every time?
Also, there's a recommendation on w3schools.com :
If you have more than one AJAX task on your website, you should create
ONE standard function for creating the XMLHttpRequest object, and call
this for each AJAX task.
Why this recommendation? I'm instead using a global XMLHttpRequest object on my page for handling all Ajax tasks.
You misunderstood W3School's recommendation. I'll highlight the relevant part:
If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task.
It says that you use one AJAX function to fetch requests. This function will deal with the inconsistencies between IE and other browsers. XMLHttpRequest in standard-compliant browsers, and ActiveXObject in IE.
I recommend to use multiple XHR objects. With one global xhr object, your application can only deal with one request at a given time. It's also error-prone (eg. XMLHttpRequest launches multiple times without initiating the onreadystatechange function).
W3schools meant something like:
function createXHR() {
try {
return new XMLHttpRequest();
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return new ActiveXObject("Msxml2.XMLHTTP");
}
}
}
var xhr = createXHR();
xhr.open('get', '/test', true);
xhr.send();
Although it's better to create a function which handles requests, such as jQuery.ajax.
It is best to use different objects for each XHR you are making. Even if there's a way of doing it, avoid it! There's no problem with creating new object for each request. If you are worried about memory leak or something of that sort, do not worry, they are all properly GC`ed.
If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task.
It actually means that you have one function that creates a new object and returns it every time you call it. It something like:
function newXHR(){
return a new instance of XHR();
}
The recommendation you highlight is saying you should have one FUNCTION which handles AJAX, rather than specifically one XMLHTTPRequest object.
I would use a different one for each question.
The common argument against this concerns the overheads involved in setting up XHRs. However this is going to be pretty much negligible in any site that uses AJAX as it was intended (i.e. not as a labouring substitute for web sockets) and, in any case, much of the same overheads would apply with re-using an XHR. You'd still have to open the connection, fire it, attach listeners etc.
Browsers vary in terms of how many connection gateways are allowed at a given time, so it's up to the browser to control what XHRs can do what. In other words, you don't have to worry about managing this aspect.
Finally, there's nothing stopping you manually deleting the XHRs after you've used them, provided they are deletable (properties of an object rather than variables).
From MDN Web Docs:
If the httpRequest variable is used globally, competing functions
calling makeRequest() can overwrite each other, causing a race
condition. Declaring the httpRequest variable local to a closure
containing the AJAX functions avoids this.
Source: https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started
I am using a pattern like this
var xhrSendBuffer = new Object();
function sendData(url, model) {
if (!xhrSendBuffer[url]) {
let xhr = new XMLHttpRequest();
xhr.onloadend = xhrDone;
xhr.error=xhrError;
xhr.onabort = xhrAbborted;
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhrSendBuffer[url] = xhr;
}
xhrSendBuffer[url].send(JSON.stringify(model));
}
function xhrDone(e) {
console.log(e);
}
function xhrError(e) {
console.error(e);
}
function xhrAbborted(e) {
console.warn(e);
}
if I end up producing a DOS on my own site because I send to the same url multiple requests I could use the xhr.readyState to see how busy it is before sending the next request, however I have yet to encounter this as an issue.

Write jquery.ajax from existing javascript

I found this article:
http://msdn.microsoft.com/en-us/library/dd251073.aspx
How could I write 'get' request using jquery.ajax?
You could use the .get() method.
http://api.jquery.com/jQuery.get/
Or just use the regular $.ajax() method (http://api.jquery.com/jQuery.ajax/), which defaults to a GET request.
It depends on whether Bing's API respects the standard ?callback=function method for specifying JSONP callbacks, but if so, then this simplified version of the Search() function should do it:
// Bing API 2.0 code sample demonstrating the use of the
// Spell SourceType over the JSON Protocol.
function Search()
{
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=Mispeling words is a common ocurrence."
+ "&Sources=Spell"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Options=EnableHighlighting"
$.getJSON(requestStr, SearchCompleted);
}
Keep in mind that neither approach is directly triggering a GET, like you might be used to in AJAX requests to a local server using XMLHttpRequest.
To circumvent the cross-domain restriction on XHR, JSONP works by injecting a new script element into your document which then causes the browser to load (via GET) and execute that remote script. That remote script's contents are a single function call to your callback function, with the entire JSON payload as its parameter.
If that doesn't work, including those Bing-specific callback options should work fine in conjunction with jQuery:
// Bing API 2.0 code sample demonstrating the use of the
// Spell SourceType over the JSON Protocol.
function Search()
{
var requestStr = "http://api.bing.net/json.aspx?"
// Common request fields (required)
+ "AppId=" + AppId
+ "&Query=Mispeling words is a common ocurrence."
+ "&Sources=Spell"
// Common request fields (optional)
+ "&Version=2.0"
+ "&Market=en-us"
+ "&Options=EnableHighlighting"
// JSON-specific request fields (optional)
+ "&JsonType=callback"
+ "&JsonCallback=SearchCompleted";
$.getJSON(requestStr);
}
Keep in mind that, at this point (and somewhat before), you aren't really using jQuery itself for much at all. Even though $.getJSON() or $.ajax() or $.get() seem like they're doing something more powerful than the MSDN example, jQuery is going to do exactly the same thing in this case (inject a script element with its srcpointed at requestStr).

Two xmlHttpRequests in a single page

I'm fairly new to ajax but am trying to implement two simple calls to dynamically changes two separate divs on a page using javascript. I have no problems using one call at a time, but when I use two it seems like the second xmlhttprequest takes over the first and writes into both divs.
I've read and tried using the fixes listed on these two other posts both neither seem to work in my case:
Sending two Ajax requests to two different PHP scripts from single javascript function
Using two xmlhttprequest calls on a page
And here is my relevant code:
function request_handler(url, params, changed_div) {
if(window.XMLHttpRequest) {
try {
req = new XMLHttpRequest();
}catch(e) {
req = false;
}
}else if(window.ActiveXObject) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
}catch(e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
req = false;
}
}
}
if(req) {
req.onreadystatechange = function(){
if (req.readyState == 4 && req.status == 200){
document.getElementById(changed_div).innerHTML = req.responseText);
}
}
req.open("POST", url, true);
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
req.send(params)
return true;
}
return false;
}
Here is the basic format of each request using the function above:
request_handler("sample.php", parameters , "sample_div");
Apologies if I'm passing something simple up here, I just can't seem to get it to work.
This question
Using two xmlhttprequest calls on a page
does answer your question.
In your request_handler function, you're using a global variable req that gets overwritten every time you call that function.
If you change it to start:
function request_handler(url, params, changed_div) {
var req;
// Rest of your function
}
you should find that it works. In this case req has a local scope and so is not overwritten when you call request_handler for the second time.
Can I also suggest that you strongly consider using the likes of jQuery, Prototype or Dojo, if you're planning on writing Ajax scripts? Writing scripts that work cross-browsers is hard to do well and these frameworks do a lot of the legwork for you.
Your req is a global variable as it is defined without the var keyword, keep that in mind.
What I think happens is that the second call overwrites the first one. This is because of the (default) asynchronous nature of the XMLHTTPRequest. Your first function call will end, but the fetching of the page is still going. The second function call then overwrites the previous request.
This however does not explain why both div get filled with the result of the second call. I must say I'm a bit lost on that one.
This is a pretty common problem, especially if you don't want to take additional measures to block further calls until the first has finished loading. Its a bigger subject that I can cover in a post but there are several examples on the web of an "Ajax Queue" that effectively manages the order of requests received.
jQuery has a plugin for managing queues and I'm certain that most other JavaScript frameworks such as Prototype and MooTools will as well. If you're wanting to stick with raw JavaScript I would take a look at this web page:
http://www.cmarshall.net/MySoftware/ajax/index.html
He implements a queue very effectively and has an excellent example of its use.

Categories

Resources