Saturday, 24 December 2011

Jquery Ajax Recursive call

We simplifies a large task into pieces and work them out easily. For example if you need to send 1000 emails at a time, there may be inconveniences to perform this large task like time out or cpu overload etc. For this reason you may break the mailing list in chunks 50 emails per list or whatever you prefer. Then you can run the script 2o times to finish your job. This can be done using AJAX. I have created an example to demonstrate this.

HTML Interface:

<div class="widget">
<h3>Mail</h3>
<div class="inner" >
<center>
<input type="button" id=" button" value="Mail" />
</center>
<div id="mailer" style="display:none;">
<center>
<h4 id='sending'>Sending ...</h4>
</center>
<div>
<div id="seek"></div>
</div>
</div>
</div>
</div> 

Style the HTML:

.widget {
width: 350px;
min-height:200px;
border: 1px #AAA solid;
background-color: #FFF;
float: left;
display: inline-block;
margin: 3px;
}

.widget h3 {
background-color: #DDD;
border-bottom: 1px #AAA solid;
padding: 3px 7px;
}
.widget .inner {
padding: 10px;
}

.seekholder {
border: 2px #AAA solid;
margin: 30px;
height: 25px;
text-align: left;
}

.seek {
background-color: #48D;
height: 25px;
width: 0%;
}

.widget .sending {
margin-top: 35px;
text-decoration: blink;
}

.widget .complete {
margin-top: 30px;
color: #44F;
font-weight: bold;
font-size: 20px;
text-decoration: none;
}
 
Required Java script:

<script language="javascript">

$(document).ready(function(){

var func = function(r){
var r = eval('(' + r + ')');
var p = r.percent;
var e  = r.ending;

$("#seek").css('width',p+"%");

if(p < 100) {
$.get("/mail.php?start=" + e, func);
} else {
$('#sending').text('Complete').attr('class','complete');
}
}

$("#button").click(function(){
$(this).attr('disabled','disabled');
$("#mailer").show();
$.get("/mail.php",func);
});
});
</script>
 
PHP Code:

$start = $_GET['start'] ? $_GET['start'] : 0;

$total = sizeof($mailList);

// next 50 emails and within the range

foreach ($i = $start; $i < $start + 50, $i < $total; $i++)
{
mail($to,$subject,$message,$headers,$params);
}

$json = array(
'ending'  => $start + 50,
'percent' => (($start + 50 ) / $total) * 100
);

echo json_encode($json);

No comments:

Post a Comment

Visual comparison of the two methods, creating a simple table.

Option 1, using PHP: // PHP $html = '<table>' ;     foreach ( $data as $row ) {     $html .= '<tr>...