Wednesday 1 February 2012

multiple return values from PHP with jQuery AJAX

Sometimes we need our server to return more than 1 value to our Jquery. And those 2 values need to be presented in the page.

We can do this usgin jquery. There are 2 methods.

.getJSON()


Example:
<?php echo json_encode(array("a" => "valueA", "b" => "valueB")); ?> 

In Javascript:
$.getJSON("myscript.php", function(data) {
   alert("Value for 'a': " + data.a + "\nValue for 'b': " + data.b);
});

.ajax()


$.ajax ({     
type: "POST",    
url: "customerfilter.php",    
dataType: json,    
cache: false,    
success: function(data)    
{         $(".custName").html(data.message1);        
$(".custName2").html(data.message2);    
} });

Then you need to encode your response as a JSON Array:
 <?php echo json_encode(       array("message1" => "Hi",       "message2" => "Something else")  ) ?> 

Spliting datetime value into separate day, month, year

Jquery provides a beautiful function to do this very easily.

i.e. split()



<input type="text" id="tbDateTime" value="2010-10-18 10:06" />
<input type="text" id="tbDate" value="" />
<input type="text" id="tbTime" value="" />

<input type="button" id="btnSubmit" value="Submit" />


<script type="text/javascript">
    $(function () {
        $('#btnSubmit').click(function () {
            var dateTimeSplit = $('#tbDateTime').val().split(' ');

            var dateSplit = dateTimeSplit[0].split('-');
//year           
alert(dateSplit[2]);
//month
alert(dateSplit[1]);
//day
alert(dateSplit[0]);
     
        });
    });
</script>

Thursday 26 January 2012

Jquery no conflict method

Since a long days, i was facing a common issue with using jQuery.

i.e. Different jquery frame works that i need to run my application smoothly was conflicting with each other.

If i implement 1, the other does not function well.

At last i came across the following technique while using jquery tabs.
<script>
var $t = jQuery.noConflict();    // assign the main jQuery object to $j
$t(function() {
$t("ul.leftsiteappslist").tabs("div.css-panes > div", {effect: 'ajax', history: true});
});
</script>

Now my conflict problem is solved.

Thursday 19 January 2012

Simple facebook type jquery search engine lightning fast

Dear Friends,

I'm Swadesh, a young software engineer who is always fascinated about facebook applications.

Once i came across facebook search bar which search for friends, communities, applications, etc.



I was always wondering how the search is so quick (The result comes instantly). After a long period of research and study, i was finally able to simulate the amazing feature.

Here is the trick that worked for me

Step-1: Include Jquery and some css into your page
<script src="js/jquery.min.js">

<link href="search_style.css" rel="stylesheet" type="text/css"/>

Step-2: We will now write javascript which will collect data available at DOM, if necessary it will search through the whole database.

The javascript search idea
  • on page load, “Load all data of friends from database into DOM”
  •  Declare an array which will hold the DOM data
  • Push the DOM data into the javascript array
  • Handle the keyup event which will subsequently search for the javascipt array object. If not found it will call the ajax function which will collect data from database.
  • Push the retrieved data again into the DOM and search from there

Step-3: The div tag to hold the loaded result & the place to display the result
<input type="text" id="ipi"></input>
<div id="search_result" style="display:none;">

</div>
<div id="sr">

</div>

Wednesday 18 January 2012

jquery visitors flip counter like digital clock

I was visiting a website called stepout.com. I came across this members counter which seem to be cool. So here i explain it for you, how it is done.


Step-1 : We start by adding some jquery plugins and css to our page


 <!-- jQuery from Google CDN, REQUIRED -->
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
    <!-- My flip counter script, REQUIRED -->
    <script type="text/javascript" src="js/flipcounter.min.js"></script>
    <!-- Style sheet for the counter, REQUIRED -->
    <link rel="stylesheet" type="text/css" href="css/counter.css" />

    <!-- jQueryUI from Google CDN, used only for the fancy demo controls, NOT REQUIRED for the counter itself -->
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/jquery-ui.min.js"></script>
    <!-- Style sheet for the jQueryUI controls, NOT REQUIRED for the counter itself -->
    <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.6/themes/vader/jquery-ui.css" />
    <!-- Style sheet for the demo page, NOT REQUIRED for the counter itself -->
    <link rel="stylesheet" type="text/css" href="css/demo.css" />

Step-2 : Next job is to put some div tags where it will be displayed


<li>Increment:
            <span id="inc_value">123</span> <a href="#">[?]</a><div id="inc_slider"></div>
            <div>
                <p>This slider controls the counter increment by using the <b>setIncrement</b> method:</p>
                <code>myCounter.setIncrement(value);</code>
            </div>
        </li>

Step-3 : Our next job is to have some javascript customization


<script type="text/javascript">
    //<![CDATA[

    // Initialize a new counter
    var myCounter = new flipCounter('counter', {value:10000, inc:123, pace:800, auto:true});

    $(function(){

        /**
         * Demo controls
         */

        var smartInc = 0;

        // Increment
        $("#inc_slider").slider({
            range: "max",
            value: 123,
            min: 1,
            max: 1000,
            slide: function( event, ui ) {
                myCounter.setIncrement(ui.value);
                $("#inc_value").text(ui.value);
            }
        });

        // Pace
        $("#pace_slider").slider({
            range: "max",
            value: 800,
            min: 100,
            max: 1000,
            step: 100,
            slide: function( event, ui ) {
                myCounter.setPace(ui.value);
                $("#pace_value").text(ui.value);
            }
        });

        // Auto-increment
        $("#auto_toggle").buttonset();
        $("input[name=auto]").change(function(){
            if ($("#auto1:checked").length == 1){
                $("#counter_step").button({disabled: true});
                $(".auto_off_controls").hide();
                $(".auto_on_controls").show();

                myCounter.setPace($("#pace_slider").slider("value"));
                myCounter.setIncrement($("#inc_slider").slider("value"));
                myCounter.setAuto(true);
            }
            else{
                $("#counter_step").button({disabled: false});
                $(".auto_off_controls").show();
                $(".auto_on_controls").hide();
                $("#add_sub").buttonset();
                $("#set_val, #inc_to, #smart").button();
                myCounter.setAuto(false).stop();
            }
        });
        $("#counter_step").button({disabled: true});
        $("#counter_step").button().click(function(){
            myCounter.step();
            return false;
        });

        // Addition/Subtraction
        $("#add").click(function(){
            myCounter.add(567);
            return false;
        });
        $("#sub").click(function(){
            myCounter.subtract(567);
            return false;
        });

        // Set value
        $("#set_val").click(function(){
            myCounter.setValue(12345);
            return false;
        });

        // Increment to
        $("#inc_to").click(function(){
            myCounter.incrementTo(12345);
            return false;
        });

        // Get value
        $("#smart").click(function(){
            var steps = [12345, 17, 4, 533];

            if (smartInc < 4) runTest();

            function runTest(){
                var newVal = myCounter.getValue() + steps[smartInc];
                myCounter.incrementTo(newVal, 10, 400);
                smartInc++;
                if (smartInc < 4) setTimeout(runTest, 10000);
            }
            $(this).button("disable");
            return false;
        });

        // Expand help
        $("a.expand").click(function(){
            $(this).parent().children(".toggle").slideToggle(200);
            return false;
        });

    });

    //]]>
    </script>
</body>

Tuesday 3 January 2012

How to track online status of a user in my website like facebook

I came across this when i was developing 1 of my social website aFriend.in.

I found out a very simple solution using jQuery or Javascript
setInterval("update()", 10000); // Update every 10 seconds 
function update()
{
$.post("update.php"); // Sends request to update.php
}

Your update.php file would have a bit of code like this:
session_start(); 
if ($_SESSION["userid"])
updateUserStatus($_SESSION["userid"]);

This all assumes that you store your userid as a session-variable when users login to your website. The updateUserStatus() function is just a simple query, like the following:
UPDATE users SET lastActiveTime = NOW() WHERE userid = $userid 

So that takes care of your storage. Now to retrieve the list of users who are "online." For this, you'll want another jQuery-call, and another setInterval() call:
setInterval("getList()", 10000) // Get users-online every 10 seconds 
function getList()
{
$.post("getList.php", function(list)
{ $("listBox").html(list); });
}

This function requests a bit of HTML form the server every 10 seconds. The getList.php page would look like this:
session_start(); 
if (!$_SESSION["userid"]) die; // Don't give the list to anybody not logged in
$users = getOnlineUsers(); /* Gets all users with lastActiveTime within the last 1 minute */
$output = "<ul>";
foreach ($users as $user)
{
$output .= "<li>".$user["userName"]."</li>";
}
$output .= "</ul>";
print $output;

That would output the following HTML:
<ul> <li>Jonathan Sampson</li> 
<li>Paolo Bergantino</li>
<li>John Skeet</li> </ul>

That list is included in your jQuery variable named "list." Look back up into our last jQuery block and you'll see it there.

jQuery will take this list, and place it within a div having the classname of "listBox."
<div></div>