Thursday, 15 July 2010

Retriggering javascript default event after AJAX response -



Retriggering javascript default event after AJAX response -

i have tab-based set-up, tab content beingness loaded asynchronously.

<nav> <ul> <li><a href="/default" class="handle current" data-handle="default">overview</a></li> <li><a href="/services" class="handle" data-handle="services">services</a></li> <li><a href="/clients" class="handle" data-handle="clients">clients</a></li> </ul> </nav> </div> <div class="tab selected" data-handle="default" data-populated="true">some stuff in here.</div> <div class="tab unselected" data-handle="services" data-source="/services-snipet" data-populated="false"></div> <div class="tab unselected" data-handle="clients" data-source="/clients-snipet.html" data-populated="false"></div> </div>

i have attached events handle class, can move current class , switch selected/unselected classes appropriately. however, before makes switch, checks dataset["populated"] on new tab. if false, load dataset["source"] via ajax , populate.

additionally, using event.preventdefault() part of process, not follow link on tab itself.

all of working fine.

the issue want able retrigger default event - link - if ajax request fails, or times out. there way of suspending/delaying default event until have asynchronous ajax response, can decide if want prevent or not? there alternate mechanism allow me prevent @ beginning, retrigger when ajax failure or time-out? or selection read href of this , redirect page in failure case?

(no jquery, please)

in ajax phone call populate on failiure can alter document.location.href forcefulness redirect:

demo

function ajax(event) { console.log(event); if(event.detail === 1) { event.preventdefault(); var target = event.target; var xmlhttp = new xmlhttprequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readystate == 4 ) { if(xmlhttp.status == 200){ //do normal stuff } else { //do same event without prevetion target.click(); } } } xmlhttp.open("get", "ajax.php", true); xmlhttp.send(); } }; var elements = document.queryselectorall("li a"); for(i=0; i<elements.length; i++) { elements[i].addeventlistener("click", ajax, false); }

javascript ajax events

No comments:

Post a Comment