I need to repalce the href of a 'title' class elements in the page on the basis of the 0 or x value returned from http://kasaragodyellowpages.com/pagedata.php?id=x. this url is set to 1 for testing. work currectly to ajax requests.
problem is late response and failure in when
<script type="text/javascript">
$(document).ready(function(){
$('.title').each(function() {
var url = null;
var l = this.href;
id_str= (l.replace('http://www.kasaragodyellowpages.com/index.php?page=item&id=',''));
var loadUrl = "pagedata.php";
$.get(
loadUrl,
{id: id_str},
function(responseText){
if (responseText!=0) {
url='http://www.kasaragodyellowpages.com/index.php?page=page&id='+responseText;
console.log('data value for '+url);
}
}
);
if(url){
console.log('set data for '+url);
$(this).attr( 'href', url );
}else
{
console.log('NOT set data for '+url);
}
});
});
</script>
As in the image the ajax result is set after the setting the value from loop with out waiting for ajax success
After this i replaced with when
<script type="text/javascript">
$(document).ready(function(){
$('.title').each(function() {
var url = null;
var l = this.href;
id_str= (l.replace('http://www.kasaragodyellowpages.com/index.php?page=item&id=',''));
var loadUrl = "pagedata.php";
$.when($.get(
loadUrl,
{id: id_str},
function(responseText){
if (responseText!=0) {
url='http://www.kasaragodyellowpages.com/index.php?page=page&id='+responseText;
console.log('data value for '+url);
}
}
))
.then(if(url){
console.log('set data for '+url);
$(this).attr( 'href', url );
}else
{
console.log('NOT set data for '+url);
});
});
});
</script>
But this didn't work