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);

Friday, 23 December 2011

jQuery AJAX functions (load(), $.get(), etc.) are not loading new page versions problem


Today I would like to share with you a quick solution to the common problem when your AJAX calls to some page that changes over time is not being loaded to your page. In other words, jQuery or your browser is not loading new version of the page.

This problem is common in Mozilla Firefox (FF). Internet Explorer (IE) users I believe, do not experience this problem. Usually it occurs when you use jQuery AJAX functions in javascript setInterval() method. Basically, what happens is that Firefox can not see the changes been made to the page and thinks it’s the same with the old one. So Firefox loads it from cache and you don’t see the new version of your page. To resolve this issue, you should simply add a random string to the request like below.
The solution:
 
// Reload mypage.html every 5 seconds
var refresh = setInterval(function()
{
    // Minimized code, suggested by Kovacs
    $('#mydiv').load("mypage.htm?" + 1*new Date() );
}, 5000);

Thursday, 22 December 2011

Cross domain AJAX querying with jQuery


This post IS NOT about jQuery’s JSONP support. This post is about how to make AJAX queries to domains other then yours. Basically how to achieve cross domain scripting with jQuery. The technique will help you resolve the access to restricted uri denied" code: "1012 problem.

Using this method for cross site scripting you will be able to:
  1. Make AJAX queries to any domain even those that differ from your own;
  2. Use any of $.get(), $.post(), $.ajax(), $getScript(), etc. jQuery AJAX functions as your query method.
But all these does not come free, you will need to put a proxy to between you and the rest of the world. This cross domain querying solution works because you actually loading the content from your own domain. You request the URL and the proxy script on your server actually loading the content from the internet and passing it over to you.
I created a sample PHP proxy that I used to get related news RSS feed for one of my projects.

The PHP script to use as a cross domain scripting proxy:

<?php// Set your return content type
header('Content-type: application/xml');
// Website url to open
$daurl = 'http://feeds.feedburner.com/jQueryHowto';
// Get that website's content
$handle = fopen($daurl, "r");
// If there is something, read and return
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        echo $buffer;
    }
    fclose($handle);
}
?>
 
 
I named the file proxy.php and made my AJAX request to this url. Here is a jQuery code example:
$("#rssFeeds").load("path/to/proxy.php", function(){
  // Some callback functions
});
And this is how I overcame the jQuery cross site scripting problems. The bad news is that not all web hosting companies allow fopen() to other domains, but enable it on request.

Wednesday, 21 December 2011

AJAX update content every X seconds


 In this fallowing Example, we are going to update our page content using AJAX and of course we love AJAX in jQuery flavor. So key to this functionality is JavaScript's built-in setInterval() function. It lets you to run some javascript function every X seconds. For example, the following code would pop alert box every five seconds:

setInterval( "alert('Hello')", 5000 );

Now consider we want to update shouts in our shoutbox every 10 seconds.
 
function updateShouts(){
    // Assuming we have #shoutbox
    $('#shoutbox').load('latestShouts.php');
}
setInterval( "updateShouts()", 10000 );

The code above will run every 10 seconds (10,000 ms) and update the contents of #shotbox with new shouts.

Tuesday, 20 December 2011

JQuery Ajax Preloader


The following example explains how can we display a loading image while requested content is being loaded by one of the jQuery's AJAX functions. Here is what happens:
  1. Something triggers AJAX request (like "search" button click);
  2. We put the loading image or a text that ask for user patience to the place where we would later insert the loaded content (or anywhere else);
  3. After remote content is fully loaded, we remove/hide the loading image/text and insert the loaded content.
To make it more apparent, imagine we have HTML page with this markup:
 
<button id="btnLoad">Load Content</button>
<div id="content">
  Please click "Load Content" button to load content.</div>

We want to load content when a user clicks on the "Load Content" button. So we need to bind a click event to that button first and make AJAX request only after it is fired.
 
$("#btnLoad").click(function(){
    // Make AJAX call
    $("#content").load("http://example.com");
});

The above code loads contents from http://example.com into the <div id="content">. While the page is being loaded we want to display our animated GIF image in the "content". So we could further improve our code like so:
 
$("#btnLoad").click(function(){

  // Put an animated GIF image insight of content
  $("#content").empty().html('<img src="loading.gif" />');

  // Make AJAX call
  $("#content").load("http://example.com");
});

The .load() function would replace our loading image indicator with the loaded content.

Important note:

You might be using jQuery’s other AJAX functions like $.ajax(), $.get(), $.post(), in this case use their callback function to remove loading image/text and append your loaded data.

PHP Ajax Simple Programming

First We will build a simple ajax library. Then, write a page to load the ajax library. This is very basic application. You can still extend it for more complex web.
Ok, for this practice, we need 3 file (I create within www/test/ajax directory):
  1. ajax.js -> as ajax library
  2. test.php -> as main page
  3. home.html -> will be loaded as content
First, write below line codes within ajax.js

function callAJAX(url, pageElement, callMessage) {
          document.getElementById(pageElement).innerHTML = callMessage;
          try {
            req = new XMLHttpRequest(); /* e.g. Firefox */
          } catch(e) {
              try {
              req = new ActiveXObject("Msxml2.XMLHTTP");
       /* some versions IE */
              } catch (e) {
                  try {
                  req = new ActiveXObject("Microsoft.XMLHTTP");
      /* some versions IE */
                  } catch (E) {
                     req = false;
                  }
              }
          }
        req.onreadystatechange = function() {responseAJAX(pageElement);};
        req.open("GET",url,true);
          req.send(null);
   
      }
   
    function responseAJAX(pageElement) {
        var output = '';
        if(req.readyState == 4) {
             if(req.status == 200) {
                  output = req.responseText;
                  document.getElementById(pageElement).innerHTML = output;
                }
           }
       }

*-------------------**-------------**--------------**--------------------------*

then, we create test.php, enter following codes:

<html>
<head>
 <SCRIPT language="JavaScript" SRC="ajax.js"></SCRIPT>
</head>
<body onload="callAJAX('home.html','displaydiv')">
<table>
<tr>
<td id="displaydiv"></td>
</tr>
</table>
</body>
</html>
 
 *-------------------**-------------**--------------**--------------------------*
 
 last, we create home.html, enter following line code: 
 
front page test
 
Now, point your browser to http://localhost/test/ajax/test.php, you will get the output.

Tuesday, 6 December 2011

Create table parti-colored in PHP


Create table parti-colored

When select the data in the database to create a table. A row, alternating colors to make
available information in the table more easily.

Example

<style>
.odd{background:#CCC;}
.even{background:#FFF;}
</style>

<table>
<?php
$bg = "odd";
for($i=0;$i<10;$i++)
{
    echo "<tr class='$bg'>";
    echo "<td>&nbsp;</td>";
    echo "</tr>";
     if($bg == "odd")
    {
        $bg = "even";
    }
    else
    {
        $bg = "odd"; 
    }
}
?>
</table>

Saturday, 3 December 2011

Javascript to show how many characters are remaining to enter in textbox or textarea


Today we will be seeing a javascript which will help us to show how many characters are remaining for a textbox or textarea,As soon as the user starts typing in a textbox or textarea, then we will show how many characters are remaining for entering into the textbox.

Here we are creating a simple textbox, and we are specifying the "maxlength" of the textbox to 20.

<label for="mytextbox">Your Name : </label>  
<input type="input" id="mytextbox" maxlength="20" onkeyup="javascript:countCharacters('mycounter',20,'mytextbox')">  
<span id="mycounter">20</span>  

And "onKeyUp" event of the textbox we are calling a javascript function "countCharacters()".
we will be writing a standard function which accepts only some parameters and rest of the processing will be done in the function.
To this function we have to pass 3 parameters1) id of the span - where counter will be shown when user types something2) max_chars - length of the textarea which we specified in maxlength="20"3) myelement - the id of the textbox where user types text
The function is as below

function countCharacters(id,max_chars,myelement) 
counter = document.getElementById(id); 
field = document.getElementById(myelement).value; 
field_length = field.length; 
 if (field_length <= max_chars)  {    
// Here we Calculate remaining characters    
remaining_characters = max_chars-field_length;  
  // Now Update the counter on the page 
   counter.innerHTML = remaining_characters; 
  } 
 }  

Now you can use this function anywhere, without a need to modify this function.

The full code to try out is here

<script type="text/javascript"> 
function countCharacters(id,max_chars,myelement) 
counter = document.getElementById(id); 
field = document.getElementById(myelement).value; 
fieldfield_length = field.length; 
 if (field_length <= max_chars)  {    
// Here we Calculate remaining characters   
 remaining_characters = max_chars-field_length;    
// Now Update the counter on the page  
  counter.innerHTML = remaining_characters;  } 
 } </script> 
 
<label for="mytextbox">Your Name : </label> 
<input type="input" id="mytextbox" maxlength="20" onkeyup="javascript:countCharacters('mycounter',20,'mytextbox')"> <span id="mycounter">20</span> 

Javascript Acceleration


<html>  
<head>  
  <script type="text/javascript">  
var c=-1;  
var tmr;  
ntimer=1000;  
var ArrColor=new Array();  
ArrColor[0]="green";  
ArrColor[1]="blue";  
ArrColor[2]="red";  
ArrColor[3]="#ffffff";  
function showpos()  
{  
if(c==3) c=0;  
else c++;  
if(ntimer<=5) ntimer=1000;  
else ntimerntimer = ntimer-5;  
document.body.style.backgroundColor=ArrColor[c];  
clearTimeout(tmr);  
tmr=setTimeout("showpos()", ntimer);  
}    
tmr=setTimeout("showpos()", ntimer);  
</script>  
</head>  
 <body>  
<p>Run this program, and watch it accelerate, slowly and slowly.</p>  
</body>  
</html> 


create socket in php


A socket connection can be created in php using the code snippet below. 
This code snippet also shows how to write into a socket and read from a socket using php.
.......
.......
$SERVER_IP = 'x.x.x.x';
$SERVER_PORT = 'yy';
$Server = socket_create(AF_INET, $SOCK_STREAM, $SOL_TCP);
if($ServerConnected = @socket_connect($Server, $SERVER_IP, $SERVER_PORT))
{
@socket_write($Server , 'hello');
@socket_read($Server , 256);
........
}
.......
.......


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

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