JavaScript · jQuery

{JavaScript} Things that may stuck you: Ajax Cache Problem

Symptoms:

  1. Ajax response data remain unchanged for same URL
  2. Page is not reloading after Ajax request

The Story: 

Few days ago, when we were using pure JavaScript (without using any JS framework), faced an interesting (though very common and basic) problem –

“Pages are not being reloaded/ refreshed after contents are updated by AJAX” that means AJAX request always returns same data from server for same URL although data has already been changed. But, more interestingly in Mozilla FIREFOX it’s working fine whereas I.E (internet explorer) showing same output.

After debugging, it was clear that whenever request URL of Ajax is exactly same as previous request, it loads the output from cache.

Example:

var xmlhttp;
	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) {
			//console.log(xmlhttp.responseText);
			alert(xmlhttp.responseText);
		}
	}
	xmlhttp.open("GET","ajax.html?q=test");
	xmlhttp.send();

Now create a page named “ajax.html” and put a small text within that page (without any html). Like-

My response text1

Now run your testAjax.html file in IE, you will get an alert saying “My response text1”

Now change the text in ajax.html file, for example “My response text2”

Now run your testAjax.html file again, you will get same alert saying “My response text1”

Solution:

Perhaps the best and the easiest solution is to change the URL every time. Don’t afraid, this is very simple, just add a URL variable with random value using JavaScript Math.random() function.

JavaScript:

In our example, we can just add it with our URL as –

xmlhttp.open("GET","ajax.html?q=test&rnd="+ Math.random());
JQuery:

In jQuery, you can disable Ajax caching as its own way, like-

$.ajaxSetup ({cache: false});

//or

$.ajax({
    url: 'test.html',
    cache: false,
    success: function(html){
       $('#results').append(html);
    }
});

If cache is set to false, jQuery itself  appends a query string parameter, “_=[TIMESTAMP]”

ExtJS:

ExtJS always handle it by itself appending a parameter _dc=[RANDOM-NUMBER]

-:-

Note: This post is part or detail explanation of my earliear  post – {JavaScript} Things that may stuck and irritate you

This post is copied from my first blog which was posted on May 7, 2008.


Advertisement
JavaScript · jQuery

{JavaScript} Things that may stuck you: Object Type Variable Assignment

Symptoms:

  1. Variable’s value is changing unexpectedly
  2. One element or component is changing when value of another element or component has been changed.

The story:

Few days ago, we faced a peculiar problem. My colleague (Al-Amin Rubel) was working a web-app where he coded pretty much complex use of jQuery.

First he collected a JSON response by AJAX request, which he used it as original view. Then, took (assigned) part of the JSON object to another variable. This new variable had been used to accept user changeable data. That means when user input or change any data he put it into this object variable.

But, the problem was- when he changed the new object variable or its any property, the original variable was also been changed.

Example: 

var x = {a:'ABC'};
var y = x;
y.a = 'XYZ';
console.log(x.a);
console.log(y.a);

If you are not familiar with JavaScript object copy/assignment issue, you definitely expect output of first console is “ABC” and second is “XYZ”. But, here both outputs are ‘XYZ’. Because, In JavaScript any kind of Object or Array type variable is assigned/copied by reference (not value)”. That means, all assigned or copied variable will actually access same variable. So if any property of any one of those variables been changed, all variables will also be changed.

Here, y variable is in fact referencing variable x.

Even, if you assign or copy part of an object which is also an object type it will also copied by reference. Look at the following example-


var A = {
	name: 'Store',
	items: [{
		name: 'Apple',
		type: 'Fruit',
		condition: {
			physical: 'good',
			color: 'very good'
		}
	}]
};

var newA = A.items[0];
newA.type = 'Vegetable';

console.log(newA.type);
console.log(A.items[0].type);

So, here both console output will be “vegetable”.

Solution:

Actually there is no JavaScript’s built-in way to copy an Object type variable. So, we have to create our own way.

JavaScript:

// this example is taken from A. Levy’s excellent answer of an stackoverflow’s question
function clone(obj) {
    // Handle the 3 simple types, and null or undefined
    if (null == obj || "object" != typeof obj) return obj;

    // Handle Date
    if (obj instanceof Date) {
        var copy = new Date();
        copy.setTime(obj.getTime());
        return copy;
    }

    // Handle Array
    if (obj instanceof Array) {
        var copy = [];
        for (var i = 0, var len = obj.length; i < len; ++i) {
            copy[i] = clone(obj[i]);
        }
        return copy;
    }

    // Handle Object
    if (obj instanceof Object) {
        var copy = {};
        for (var attr in obj) {
            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
        }
        return copy;
    }

    throw new Error("Unable to copy obj! Its type isn't supported.");
}

JavaScript frameworks do this their own way and let users some cloning methods. Like-

JQuery:

  var copiedObject = {};
  jQuery.extend(copiedObject,originalObject);

ExtJS:

  Var copiedObject = Ext.clone(originalObject);

Note: This post is part or detail explanation of my earlier  post – {JavaScript} Things that may stuck and irritate you

ExtJS · JavaScript · jQuery

{JavaScript} Things that may stuck and irritate you

Is there any web site or web based application which does not use JavaScript? May be yes but how often? In the other word, is there any developer who works in website or web application development (using PHP/C#.Net/ASP/JSP or any language), but need not to deal with JavaScript?

If somehow you are related to internet you have to deal with JavaScript. But, arguably JavaScript is one of the most unfriendly and sometimes annoying language to work because of its debugging (specially before Firebug) and cross browser compatibility.

In this post, I will try to include JavaScript related those issues which I faced and felt as little bit critical. I am sure, most novice JavaScript developers like me have to spent lots of time to find and solve these type of issues.

This is the summary post of the those issues, I will explain and elaborate each issue with example withing my following posts.

So, here is the list of those issues that I feel, may stuck and irritate you sometimes:

  1. Object Type Variable Assignment 
  2. Ajax Caching Problem 
  3. Sequence of event firing
  4. Variable/Object scope and overriding
  5. Multiple elements with same ID
  6. Script injection in your page
  7. Dynamic page sizing
  8. Ajax request and JavaScript loading from other domain
  9. Browser dependability
  10. JavaScript disable in user browser

P:S: I will be updating this list whenever I get stuck with something.
JavaScript · jQuery

What is the difference between asynchronous (AJAX) and synchronous request?

This post is copied from my first blog which was posted almost 4 years ago.

Now-a-days, this is a very common question  that being asked in most interview for beginners level developers – What is the main strength of AJAX? Or why and when should we use AJAX in web application?
And the most common answer is – “AJAX does not refresh or reload the whole page”.

But, the more perfect answer is – “AJAX is an asynchronous technology where others request are synchronous.”

So, what is the difference?

In a word, a program does not wait for response after requesting an asynchronous call whereas synchronous does so.

Here is a simple example –

function check() {
  var a=0;
  a = getStatus(“getstatus.php?id=5”);
  if(a==1) {
     alert(“active”);
  } else {
     alert(“not active”);
  }
}

Here, getStatus() function sends a AJAX request to the server with “getstatus.php?id=5” url and the php file decides (from database may be) the status and output/response as 1 or 0.

But, this function will not work properly. It will alert “not active” instead of “active”. And yes, that is for the asynchronous request.

The reason is – when a = getStatus(“getstatus.php?id=5”); line is being executed program does not wait for the response of setStatus() function. So, value of keep unchanged or set to null.

So, how should we work with asynchronous request?

Of course, using callback function. Callback function is that function which is triggered when the request completes to get the response (or as defined).