PHP and ajax easy with json and jquery
Getting data back and forth between a php script and your javascript may seem like a chore. Luckily php can talk json pretty easily ( with the appropriate functions enabled of course ).
Lets build a simple call that submits a number to php for calculation.
<script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $('#calc_btn').bind('click',function(){ $.ajax({ url: 'calc.php' ,type: 'post' ,dataType: 'json' ,data: { num: $('#num_val').val() } ,success: function(data) { $('#result').html( 'Result: '+ data.result ); } }); }); }); </script> <input type="text" id="num_val" /> <input type="button" id="calc_btn" value="Calc" /> <div id="result"></div>
And for the php file calc.php that will do the calculations
if ( array_key_exists('num',$_POST) ) { $i = intval($_POST['num']); $i++; $data = array( 'result' => $i, ); echo json_encode($data); }
This is a very simple example. The exact functionality of the example can be done using more succinct jquery calls ( using .load() for example ), but this example will give you a good starting point to build on top of for more complex applications. JSON makes the data transfer simple.