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>