Different types of ajax implementation - javascript

i have just started working on ajax for my chat application which i am making in php.
While studying ajax online I cam across 2 ways in on different sites where ajax had been implemented.
What is the difference between these 2 implementations of ajax?
Any help will be greatly appreciated :)
First Implementation-
<script type"text/javascript">
$(document).ready(function() {
var dept = '<?php echo $deptId; ?>';
var interval = setInterval(function() {
$.ajax({
url: 'scripts/php/Chat.php',
data: {dept:dept},
success: function(data) {
$('#messages').html(data);
}
});
}, 1000);
});
</script>
Second Implementation-
<script language="javascript" type="text/javascript">
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age ;
queryString += "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}

Functionality-wise, it could be argued that there is no difference between them.
That said, the first "difference" between them is that the first method is using JQuery, and thus to use it, you need to have the JQuery Javascript library included in your project or the page where you need the ajax functionality. The second method, however, uses "plain ole Javascript".
Again, the first (JQuery) method, handles a lot of the "dirty" details for you, providing you with an ($.ajax) interface and requiring only that you pass in some parameters:
url : The URL you wish to call
data : The data (GET or POST) you wish to pass to the URL
success : The callback function that should be executed when the ajax request successfully returns.
In doing this, this method abstracts the internal implementation from you. For example, it handles for you the following:
browser-sniffing/capabilities detection
readyStateChange (event) checks
and some other mundane details.
Besides, also, using the second method, you can rest-assured that your code will mostly work in the majority of scenarios (if not all), if you "honour" the interface specification of the $.ajax call. Using the second method, however, you'll need to do a lot of testing and checks to ensure that your code works across all browser and platform types.

Your first code use jQuery. JQuery is a rich js lib that helps you coding quickly. See http://api.jquery.com/ (and in your particular case : http://api.jquery.com/jQuery.ajax/
Your second code is only javascript without any help from other library. It uses the XMLHttpRequest wich allows ajax call. See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
The use of jQuery is easier but some find it "overkill" :)

Related

Open XML with jQuery with maximum browser compatibility

We have a webpage using this code :
var xhr = new window.XMLHttpRequest();
// XHR for Chrome/Firefox/Opera/Safari.
// Create the XHR object.
xhr.open("GET","prp.xml", false);
xhr.send();
xmlDoc=xhr.responseXML;
It opens an XMLHttpRequest to get our XML file and then drops the result into the xmlDoc variable. I would like to know if it's possible to do that same operation using jQuery v1.11.0 and that the xmlDoc variable will still be usable by the rest of the code (aka still compatible with regular JS).
Depending on the user in here, people are using Firefox, Chrome, internet explorer 8, 9 or 10. I have read that internet explorer under 10 cannot use XMLHttpRequest, and i am pretty bad/lost with this whole jQuery thingy.
Thanks!
I'm not sure how regular JS handles XML, but an Ajax-call via jQuery is as simple as:
var xhr_variable;
$.ajax({
url: "your.xml",
success: function(data) {
console.log("working");
xhr_variable = data;
}, error: function(err) {
console.log("not working");
}
});
If you are new to Ajax, I recommend using error to check if it works or not. If works without problem, you can use the following:
var xhr_variable;
$.ajax({
url: "miep.xml",
success: function(data) {
xhr_variable = data;
}
});
Your XML-file will be assigned to your variable (if used in the correct scope).
Please note that for security reasons Ajax will only work if you call documents that are hosted on the same domain. (example.com can get documents for example.com, but not from example2.com).

php not returning any result to javascript ajax object

I'm trying to use ajax, I've used it before, copied the code from my previous html file and altered the values sent, php file to process the code and I'm using the POST method. However, the php script does not return anything to the html page. I've checked all i can, so I'm here now.
function look () {
var x = document.getElementsByTagName('option')[document.getElementById("region").selectedIndex].value;
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// modal section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById("accordion");
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
ajaxRequest.open("POST", "search.php", true);
ajaxRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
alert(x);
ajaxRequest.send("region=" + x);
}
The php code is a simple
<?php
echo "The world is blue.";
?>
yet, it returns nothing to the chosen div.
You've probably not posted enough information for us to answer your question. But, I acknowledge that you probably are not sure what questions you need to ask in the first place.
First, I must agree with #cgf. jQuery or the alike will make this easier.
But lets focus on the problem at hand. We need to know what is happening behind the scenes.
The best way to do this is through a developer tool bar such as firebug. Chrome has one built in.
So, load up chrome and hit F12. This should bring up a very busy looking pane on the bottom of your window. Select the Network tab and then request your page / trigger your javascript. What output do you get in the network tab? Mainly, under status do you get 200, 500 (server error) or perhaps 404 (not found)? Update your question above with what you see / get.
My hope is that this should point you in the right direction.

difference from using ajax from jquery and javascript

i cant find an answer to this
i have been learning ajax lately but i learned how to do it all in javascript
now i go swiming around ajax question here and almost all are using jquery
so i end up confused. should i use normal javascript or do it through jquery?
so what are the differences?
this is my normal approach
var xmlHttp = createXmlHttpRequestObject(); //you first create the object to this function global
function createXmlHttpRequestObject() //here you instruct the function
{
var xmlHttp; //here you tell it to use the local variable not the global version of it because this returns to the global with the propper values
if (window.XMLHttpRequest) //if the "window" or browser is aware of this Object 90% of browsers
{
xmlHttp = new XMLHttpRequest(); // if true then the variable is now equal to the heart of ajax
}
else //for internet explorer
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp; //we return it back to daddy the global variable this objects does everything
//this object is everything in ajax for the most part
}
function process() //function that gets called on load of the body
{
if(xmlHttp) //if its not void or if you can run ajax
{
try //try catch statement are sort of required for the heart of things like ajax and server communication
{
xmlHttp.open("GET", "bacon.txt", true); //here 1st type of call 2nd from where 3rd
//is it true assyscronly or at the same time
//it does not start the connection to the server, its only sets up settings for the connection
xmlHttp.onreadystatechange = handleServerResponse; //anytime something changes[propertie]
//i want to call that function handleserverresponse
//begin communication
xmlHttp.send(null); //this is what communicates to the server makesure on ready statechane before this
//if the server responds you want to make sure everything is taking care of like what function onready state change is it going to call
//or what to do like open a text file in this case
} catch(e)
{
alert( e.toString() ); //alert the error message as a string on a popup
}
}
}
//handling the server response
function handleServerResponse()
{
theD = document.getElementById('theD'); //get the div in a var
if(xmlHttp.readyState==1) //if the connection to the server is established
{ //google crhome may not show this one, some browsers ignore some states
theD.innerHTML += "Status 1: server connection established<br>";
}
else if(xmlHttp.readyState==2) //request received, hey client i am the server and i received your request
{
theD.innerHTML += "Status 2: request reveived <br>";
}
else if(xmlHttp.readyState==3) //while is doing its thing
{
theD.innerHTML += "Status 3: processing request <br>";
}
else if(xmlHttp.readyState==4) //your request is finished and ready
{ //it means your response is ready but doesnt guaranteed no trouble
if(xmlHttp.status==200) //if the status is 200 then is succesufll
{
//IF everthing finally good THE GOOD PART
try //put all your calls on a try statement REMEMBER
{
//get the txt file as a string
text = xmlHttp.responseText; //response text n a normal string
theD.innerHTML += "Status 4: request is finished and response is finished";
theD.innerHTML += text;
}catch (e)
{
alert( e.toString() );
}
} else //for the other statuses like 404 else somehting went wrong
{
alert( xmlHttp.statusText ); //this will give you a status report on the wrong
}
}
}
jQuery simply wraps all of the XmlHttpRequest calls into a simple to use library. In the guts of jQuery you will see code that creates the XmlHttpRequest objects.
You can see the code that does this here:
https://github.com/jquery/jquery/blob/master/src/ajax/xhr.js
The nice thing about using a framework like jQuery is that they handle a lot of the browser idiosyncrasies for you. They also handle a lot of the edge cases you might not think about when writing your code.
Using jQuery is just for ease of use. If you prefer doing it the javascript way then carry on doing that.
jQuery ajax calls do exactly the same as what you are doing but jQuery is a javascript framework which simplifies what you write.
jQuery is a javascript framework which contains library of simplified functions compared to the Native Javascript. One of the functions is the XMLHttpRequest.
This way we just need to implement functions that is needed to implement without needed to write the traditional codes to setup the AJAX system to work
You may learn more about jQuery ajax here:
http://api.jquery.com/jQuery.ajax/

AJAX polling and looping

My project is basically like a Reddit feed that updates in real-time. I'm trying to use AJAX to poll the server at intervals for updates on 15 items at a time.
I wrote a for loop but it caused the browser to lock up (I'm guessing too many XHRs?).
How can I poll each item on the Reddit-esque feed without locking up the browser? What is the most efficient way to do this?
Should I use long-polling if there are 100+ clients using the web app at the same time? Or should I opt for smart polling (increasing the wait time between requests if no data)?
Thanks! I'm still new to AJAX!
for (var i=0; i < id_array_len; i++) {
// Grab current reply count
var reply = $("#repl"+item_id).html();
var url= *php function here*
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser does not support AJAX!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if (ajaxRequest.readystate == 4){
live_feed_data_tot = ajaxRequest.responseText;
if (live_feed_data_tot.trim() == "no change" || live_feed_data_tot.trim() == "no meme" || live_feed_data_tot.trim() == "no response"){
console.log("(no update)");
} else {
var live_feed_data = live_feed_data_tot.split(',');
if (live_feed_data[1] == 'reply') {
// Reply count has changed
new_reply = live_feed_data[0].trim();
// Update actual number
$("#repl"+item_id).html(new_reply);
}
}
}
}
ajaxRequest.open('POST', url, true);
ajaxRequest.send();
Use longpolling with a long (appropriate for your app of course) timeout. Your call needs to be asynchronous of course. As long as there is no data to deliver, the server holds the answer back, until the timeout is about to be reached. As soon as the client gets an answer, trigger the next longpoll in your complete()-Block. This way you can minimize the number of requests.
EDIT: after seeing your code i see you use native ajax but use jQuery for selecting. I suggest you to use jQuery for your ajax requests as well (jQuery .ajax() Doku).
Your code should look something like this:
function doAjaxLongpollingCall(){
$.ajax({
url: "...",
timeout: <prettylong>,
success: function(){
//process your data
},
complete: function(){
doAjaxLongpollingCall();
}
});
}
If you are doing a lot of users, switch to socket.io and save yourself the hassle. It uses websockets (which use a push mechanism) and does fallbacks to other mechanisms like flash sockets or long polling if thats not available in the browser. Requires you to create this piece of your app in node.js though.

Ajax working only in IE

Can someone tell me which are the main differences, or aspects that I should look for, if the AJAX I'm using works perfectly on IE but does not work at all on Google Chrome or Firefox?
Are there some things that IE accept but the others dont? Or is there any code that I should add in order to works for all the browsers?
I dont know if this affect something, but I'm working with PYTHON!
Here is the code that all the Ajax functions use as base:
var xmlhttp;
var request = true;
function GetXmlHttpObject() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml12.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
return false; //or null
}
}
}
if (!request)
alert ("Error initializing XMLHTTPRequest!");
return request;
}
After doing this, I use a regular Javascript function which includes something like this:
var url = 'evaluacionDesempenoBD.py?cadena=' + cadena + '&comentario=' + comentario + '&idEvaluacion=' + idEvaluacion + '&seccion=' + seccion;
xmlhttp = GetXmlHttpObject();
if (!xmlhttp) {
alert ("Browser does not support HTTP Request");
return;
}
var xml = xmlhttp;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);'''
I hope i made myself clear
Thanks a lot!
You probably use the ActiveX AJAX object and not the native implementation supported by all browsers.
Use new XMLHttpRequest() to create an AJAX object on browsers with native implementation.
Wikipedia has an awesome article on XMLHttpRequest with some sample code that should help you get your AJAX thingie work across all browsers.
Perhaps you might be facing a problem due to browser differences with regards to the internals of the XMLHttpRequest object, particularly how you handle readystate changes. Quirksmode has a document on this.

Categories

Resources