Tag: ajax
How to abort ajax requests gracefully
by z3n on Jun.28, 2010, under Coding, Tips & Hints
Problem:
Ajax is great, everyone knows, but sometimes for network issues, server slowdowns or simply users issues request fails or keep loading for a long time. How to abort a request or all of them without needing to reload the whole page?
Solution:
First you need to throw all your ajax requests into a array, that way you can use it as api, so you can abort any “slow” requests, in my case i have a complex admin interface which sometimes bugs or get swamped with lots of requests at same time, usually due user related issues, so i added this “cancel” button which clears up all pending ajax requests, making the system more realiable. Before developing it i did a test on how it works, here’s the source:
<?php
// (c) z3n - R1V1@100628 - www.overflow.biz - rodrigo.orph@gmail.com
if (isset($_REQUEST['q'])) {
header('Content-Type: application/json; charset=utf-8'); // mandatory for jquery compatibility
if (!isset($_REQUEST['a']))
sleep(20);
echo json_encode(array("r" => 1));
die;
} else {
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var _ajax=[];
function do_dbg(msg) {
$("#dbg").prepend(msg+"<BR>");
}
function do_ajax() {
do_dbg("do ajax");
_ajax[_ajax.length] = $.ajax({data:"q=something",success:function(r,s) {
do_dbg("do ajax reply");
return;
}});
}
function do_ajax_fast() {
do_dbg("do ajax_fast");
_ajax[_ajax.length] = $.ajax({data:"q=something&a=other_thing",success:function(r,s) {
do_dbg("do ajax fast reply");
return;
}});
}
function kill_ajax() {
do_dbg("aborting all ajax");
for (var i in _ajax)
_ajax[i].abort();
}
$(document).ready(function(){
$.ajaxSetup({
url:"<?=$_SERVER['PHP_SELF']?>",
global:true,
type:"POST",
dataType:'json',
cache:false,
async:true,
timeout:12000000,
scriptCharset:"UTF-8"
});
});
</script>
</head>
<body>
<input type="button" onClick="do_ajax();" value="do ajax">
<input type="button" onClick="kill_ajax();" value="kill ajax">
<input type="button" onClick="do_ajax_fast();" value="do ajax fast">
<BR><BR>
<span id="dbg"></span>
</body>
</html>
<?php
}
?>
Have fun!
Bad Coders United
by z3n on Jan.31, 2010, under lol
Problem:
So I have this joint work where I do the frontend and another company does the backend and CRM integration of the system, I basically wrote a frontend and examples of all XMLs that backend should send to the system in order to have it working. After a week things were ready and i sent it to the backend team, and look how good they manipulate arrays:
$listai = str_replace(‘Ar’,” , $listai);
$listai = str_replace(‘Array’,” , $listai);
$listai = str_replace(‘ray’,” , $listai);
another example…
function datadma($dataz){
$dia = substr($dataz, -2);
$mess = substr($dataz, -5,2);
$ano = substr($dataz, -10,4);
return $dataz= $dia.”/”.$mess.”/”.$ano;
}
Oh man, wait, they DON’T KNOW what is an array!
How is that possible? Array is one of the first things a decent programmer is supposed to learn.
And the best, how is it possible for a company to build up a CRM system without the use of a single array? That’s like a coding challenge, specially when manipulating multiple fields and so on. And that’s not the only issue, after stating, in front of the client, that they weren’t able to work with jQuery + Ajax using XML (which they previously stated that could be worked without problems) they asked me to teach them … for free!!!!
ahahahah
Solution:
just sharing the story, there’s no solution for this :)
The Ampersand (&) XML Problem
by z3n on Sep.26, 2009, under Coding
Problem:
Having ampersands (&) on a xml makes it non-compliant, causing errors on IE.
Solution:
I’ve been looking on this issue for a while, although I had the answer already I wanted an alternate. One said that you could turn the & into & html entity or it’s ASCII code, but this just gets into another issue, since the & will still there – & & – In my case I had accents encoded as html entities, like áéíóú, which must be encoded (at least on my project) as entities to be passed as xml/json/etc. Other people noted that it’s possible to have specific entities declared on the html header, although this is a drawback, because xml will become quite big if you have too many different entities AND you will have to redeclare them on every reply.
None of the solutions I’ve found were good, so I’m posting mine.
A simple base64 encode would resolve the issue, and you only need to do it on replies, making things easier, so you send as base64 and the user with a little javascript decodes it back.
Base64 Javascript Source Code:
-
var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
-
-
function _enc(input) {
-
var output = "";
-
var chr1, chr2, chr3;
-
var enc1, enc2, enc3, enc4;
-
var i = 0;
-
do {
-
chr1 = input.charCodeAt(i++);
-
chr2 = input.charCodeAt(i++);
-
chr3 = input.charCodeAt(i++);
-
-
enc1 = chr1 >> 2;
-
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
-
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
-
enc4 = chr3 & 63;
-
-
if (isNaN(chr2)) {
-
enc3 = enc4 = 64;
-
} else if (isNaN(chr3)) {
-
enc4 = 64;
-
}
-
-
output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
-
keyStr.charAt(enc3) + keyStr.charAt(enc4);
-
} while (i < input.length);
-
-
return output;
-
}
-
-
function _dec(input) {
-
if (input == "NULL") { return ""; }
-
var output = "";
-
var chr1, chr2, chr3;
-
var enc1, enc2, enc3, enc4;
-
var i = 0;
-
-
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
-
input = input.replace(/[^A-Za-z0-9\+\/\=]/g|>, "");
-
-
do {
-
enc1 = keyStr.indexOf(input.charAt(i++));
-
enc2 = keyStr.indexOf(input.charAt(i++));
-
enc3 = keyStr.indexOf(input.charAt(i++));
-
enc4 = keyStr.indexOf(input.charAt(i++));
-
-
chr1 = (enc1 << 2) | (enc2 >> 4);
-
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
-
chr3 = ((enc3 & 3) << 6) | enc4;
-
-
output = output + String.fromCharCode(chr1);
-
-
if (enc3 != 64) {
-
output = output + String.fromCharCode(chr2);
-
}
-
if (enc4 != 64) {
-
output = output + String.fromCharCode(chr3);
-
}
-
} while (i < input.length);
-
-
return output;
-
}
Simple AJAX/xmlhttp query issue
by z3n on May.20, 2009, under Coding, Tips & Hints
Problem:
You like jQuery, however, doing simple tasks get impossible since jQuery is too massive, even packed it’s over 50kb. The alternate, script.taculo.us, is even bigger!
Solution:
Doing a simple ajax or xmlhttp request, is nothing out of this world, actually, it’s pretty easy, you just need to watch it if you do more than one on the same page, or when a error happen you might want to have a handler.
Based on quirks mode example i wrote this little function, it’s able to do a rudimentar queue and return plain text from a remote server, it’s also compatible with IE.
-
_lD=function(url){
-
if(p==1){
-
setTimeout("_lD('"+url+"')",250);
-
}else{
-
p=1;
-
x=null;
-
if(window.XMLHttpRequest){
-
x=new XMLHttpRequest();
-
}else if(window.ActiveXObject){
-
x=new ActiveXObject("Microsoft.XMLHTTP");
-
}
-
if(x!=null){
-
x.onreadystatechange=function(){
-
var r="";
-
if(x.readyState==4){
-
if(x.status==200){
-
r=x.responseText;
-
-
// manipulate your result here
-
-
p=0;
-
}
-
}
-
}
-
x.open("GET",url,true);
-
x.send(null);
-
}
-
}
-
}
Packed, this function is less than 500 bytes, much better than the 58kb of jQuery, heheh