Shortening Ajax Code - javascript

I am creating fully Ajax based website so all actions calls a different JS function therefore I am using this Ajax Code in each of my function which makes my functions a big code.
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var getData=xmlhttp.responseText;
if(getData=="something") {
/*
code goes here
*/
}
else {
/*
code goes here
*/
}
}
}
xmlhttp.open("GET","mypage.php",true);
xmlhttp.send();
So I wanted to ask should I use a different function that contains only above Ajax Code and declare my variable getData globally so whenever I need it I should call it.
Here is how I wanted to use
var getData=""; /*declaring var Globally (I read it like this dont know right)*/
function oneAjax(checkPage) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
getData=xmlhttp.responseText;
/*now check further in the function which called it*/
}
}
xmlhttp.open("GET",checkPage+".php",true);
xmlhttp.send();
}
Will it create any conflict with other running actions?
or provide me any right solution for my problem.

If you're not going to use an off-the-shelf library, you should pass a "callback" to oneAjax:
function oneAjax(checkPage, done, fail) {
...
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
done(xmlhttp.responseText, xmlhttp.status);
} else {
fail(xmlhttp.status);
}
}
};
}
Adjust the parameters passed to the callbacks to suit your requirements.
To use:
oneAjax('mypage', function(text, status) {
// success
console.log(status);
}, function(status) {
// failure
console.log(status);
});

why don't you use Jquery or something like this? Such library will much shorten your statements and this will be much easier to write.
But still if you want to do it by your own you should read about javascript promises. On msdn there is a nice tutorial how to solve your problem: Asynchronous Programming in JavaScript with “Promises”

I think using the jQuery library would be better and provide a better low level abstraction
<!-- add a protocol if on local ex: http: -->
<script src="//code.jquery.com/jquery-1.10.0.min.js"></script>
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
It also offers features like JSONP to get around cross domain issues

Related

How Can 2 onload() JavaScript Scripts be Loaded?

With this function:
function start() {
MONDUX();
Biggie();
}
function MONDUX executes, and the AJAX call returns good data and is displayed correctly.
However, Biggie() is a.w.a.l.
The result of this :
function start() {
Biggie();
MONDUX();
}
is the opposite. Biggie() works as expected, MONUX() fails.
This doesn't do any good, down in the body:
<script type="text/JavaScript">
window.onload= start();
</script>
and, this dodge is not helpful:
<body onload="start()">
and that was tried like so also
Detest cargo~cult programming and running out of ideas here. Suggestions?
These resources were all related // near hits // no cigar.
Loading javascript in body onload with 2 functions
JS and Body(Window) Onload event
JavaScript: How is "function onload() {}" different from "onload = function() {}"? That one
was fascinating but way deep waters for me...
How to onload two javascript files? meh... good, but...
?? :/~
<script type="text/javascript" >
function MONDUX(){
if (window.XMLHttpRequest)
{ // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{ // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("WhatThexBobby").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","000 8 KISS 22solo PHP.php?figure1=5&figure2=33", true);
xmlhttp.send();
alert(WhatThexBobby);
}
</script>
<script type="text/javascript" >
function Biggie(){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("FreakinEh").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","000 8 KISS solo PHP.php?figure1=5&figure2=10", true);
xmlhttp.send();
alert(FreakinEh);
}
</script>
You're assigning the request to the global variable xmlhttp, and then reassigning that variable to another request before the first one has returned. I don't know if that is causing your problem, but it's definitely going to cause a problem. It's also very bad JavaScript practice.
Simple fix is to put the line 'var xmlhttp;' at the beginning of both functions.
Edit: Just in case you didn't know this: xmlhttprequest is asynchronous. You call 'send', and your remaining statements in the script and document continue to run while the request is being sent to the server. Only after the server returns do the various callback methods (onreadystatechange, and the like) get called, and this is long after your alerts were shown.
Considering one of them is throwing some error, would it not be good idea to put them in Try Catch ? Something like,
function start() {
try
{
MONDUX();
}
catch(err)
{
// handle error
}
try
{
Biggie();
}
catch(err)
{
//Handle error
}
finally
{
// cleanup
}
}
This will ensure both runs even if one of them mis-fires.

FadeIn DIV after AJAX pull

i have this bit of nasty code :P that updates a div using AJAX, but i would love to see a fadein effect on it. The thing is, i have an image that loads and appears during the interval where the div is not showing any content yet. Analyse the bottom of it. What can i do to make it fadein?
function testing(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById("myDiv").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
$('#myDiv').html('<div style="text-align:center; padding-top:195px;"><img src="../images/loaderajax.gif" width="220" height="19" /></div>');
xmlhttp.open("GET","getuser.php?q="+str,true);
$('#myDiv').hide();
xmlhttp.send();
$('#myDiv').fadeIn();
}
If you are okay with wrapping the returned content, I would do something like this in the ajax response:
$("<div/>").html(xmlhttp.responseText).appendTo("#myDiv").hide().fadeIn();
This will allow your image to show and only fade in the new content.
Your code is all wacky and out of order with your ajax call. You're using JQuery, so take advantage of it! :)
$.ajax({
url: 'getuser.php',
data: str,
beforeSend(jqXHR, settings) {
$('#myDiv').html('<div style="text-align:center; padding-top:195px;"><img src="../images/loaderajax.gif" width="220" height="19" /></div>');
},
error:function(jqXHR, textStatus, errorThrown) {
$('#myDiv').html(textStatus + ' -- ' + errorThrown);
},
success:function(data){
$('#myDiv').hide().html(data).fadeIn();
}
});
Put the fadein() call in the code that handles the response.
Any reason why you're using jQuery for the selectors and effects and not for the AJAX?

XML Parsing not working in IE

I am trying to parse a XML file, it works perfectly in FF but dont in IE. Pls help debug this. The code is as follows.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","books.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.write("<table border='1'>");
var x=xmlDoc.getElementsByTagName("StepName");
for (i=0;i<x.length;i++)
{
document.write("<tr><td>");
document.write(x[i].getAttribute("name"));
document.write("</td><td>");
document.write(x[i].getElementsByTagName("StepStatus")[0].childNodes[0].nodeValue);
document.write("</td><td>");
document.write(x[i].getElementsByTagName("StepDescription")[0].childNodes[0].nodeValue);
document.write("</td></tr>");
}
document.write("</table>");
Your code, improved and annotated:
abstract things like XmlHttp requests into dedicated functions for reusability
always use the var keyword for declaring variables; forgetting this is a source of nasty bugs
use meaningful variable names wherever possible; single-letter names are suitable for loop counters but not for a lot else
never do synchronous HTTP requests, use callbacks instead
functions that do sanity checks first and return early tend to be less deeply nested
do not build HTML with document.write(), use the DOM instead
function getXml(url, onsuccess) {
var xmlhttp;
if (window.XMLHttpRequest) { // IE10+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // IE5 - IE9
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState != 4) return;
if (xmlhttp.statusCode !== 200 || !xmlhttp.responseXML) return;
if (typeof onsuccess !== "function") return;
onsuccess.call(xmlhttp, xmlhttp.responseXML);
};
xmlhttp.send();
}
Now we can use it as follows:
getXml("books.xml", function (xmlDoc) {
var table = e("table", document.body), // see helper function e below
steps = xmlDoc.getElementsByTagName("StepName"),
i, step, tr;
for (i = 0; i < steps.length; i++) {
step = steps[i];
tr = e("tr", table);
e("td", tr, step.getAttribute("name"));
e("td", tr, step.getElementsByTagName("StepStatus")[0].childNodes[0].nodeValue);
e("td", tr, step.getElementsByTagName("StepDescription")[0].childNodes[0].nodeValue);
}
});
// helper function to build HTML elements with the DOM
function e(name, parentNode, text) {
var elem = document.createElement(name),
textProp = elem.hasOwnProperty("textContent") ? "textContent" : "innerText";
if (text) elem[textProp] = text;
if (parentNode && parentNode.appendChild) parentNode.appendChild(e);
return elem;
}
I suspect that your problem lies here:
step.getElementsByTagName("StepStatus")[0].childNodes[0].nodeValue
Maybe you are making assumptions about the document structure that are incorrect. But unless you post your XML, this is hard to say.
i had similar problem and following code works for all browser ...the trick is use separate code XML for IE browsers or that are version of less than 10 .
so every time Ajax is call a method parseXml is called with input parameter XML Dom or text, depending on browser .... and if current browser is IE, it upload XML doc, process it according to Microsoft standards and return XML and rest of processes in Ajax carries on as expected!!
note : browser.msie is not supported in jQuery 1.9 but you can add jquery-migrate-1.2.1.min.js in order to make it compatible or use userAgent and find which is current browser
$.ajax({
type: 'GET',
url: 'XML_file.xml',
dataType: ($.browser.msie) ? "text" : "xml",
success: function (xml) {
var processedXML = parseXml(xml);
$(processedXML).find('my record').each(function () { //code }
});
function parseXml(xml) {
if ($.browser.msie) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "XML_file.xml", false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
xml = xmlDoc;
}
return xml;
}

AJAX: How to use TWO xmlHttpRequest in parallel in ONE function?

How should I do this?
function(id,id2){
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
First Request:
xmlhttp.open("GET", "http://example.com/ajax.php?id="+id, true);
xmlhttp.send();
Second Request:
xmlhttp.open("GET", "http://example.com/ajax2.php?id2="+id2, true);
xmlhttp.send();
}
Because in this way doesn't works.
I want to make it in plain javascript, so please do not post answers with jQuery or any library etc.
Thanks
It should work if you create a new xmlhttp object. Currently you are attempting to reuse the same object, which is already performing a query so it will not work.
if you are looking for classic javascript style you can use as the following. But use jQuery as it's simple and comprehensive. The one thing to be noted is that the "xmlhr" should be in method (callAjax) scope.
function callAjax(url) {
var xmlhr;
if (window.XMLHttpRequest) {
xmlhr = new XMLHttpRequest();
} else {
xmlhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhr.onreadystatechange = function () {
if (xmlhr.readyState == 4 && xmlhr.status == 200) {
alert(xmlhr.responseText);
}
}
xmlhr.open("GET", url, true);
xmlhr.send();
}
function myFunction(id1, id2) {
callAjax("http://example.com/ajax2.php?id2=" + id1);
callAjax("http://example.com/ajax2.php?id2=" + id2);
}

How to create a xmlhttp request?

var url="display.php?vote="+grade;
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
document.getElementById("txtHint").innerHTML=xmlHttp.responseText
}
}
This piece of code fails to send out the request. How to create a xmlHttp correctly?
<script type="text/javascript">
function ajaxFunction()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
}
</script>
this piece of code is available in link text you can learn basics here like i did. hope this helps.
Here is a "80%" solution.
function GetXHR()
{
try
{
if (window.XmlHTTPRequest)
xmlHttp = new XmlHTTPRequest()
else
xmlHttp = new ActiveXObject("MSXML2.XMLHTTP.3.0")
}
catch(e) { }
}
var xmlHttp = GetXHR()
if (xmlHttp)
{
// Proceed with xmlHttp usage.
}
Edit
Note I tend to avoid the old ProgID "Microsoft.XMLHTTP" in favour of the one I have used because this later ProgID has a more predictable behaviour and is ever so slightly more secure. However if you want wider compatiblity with really old Windows machines (I'm talking out-of-support stuff) then you could use the older one in your specific case.
var xmlHttp=new(window.ActiveXObject?ActiveXObject:XMLHttpRequest)('Microsoft.XMLHTTP');

Categories