Add to Favorites

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.

Comments

04/25/2011 8:22am
Nice explanation of jQuery, JSON ve PHP solution. Thanks a lot
CT
08/12/2011 3:01pm
I am trying to do a calculation with json data array. What I have is an autocomplete that dynamically creates a quantity and selectobox filled with key,vals. I have an add button that clones the process all over. It works fine but I am trying to figure out how to use json to add up all the values for each individual keys,values. Any help appreciated.
10/04/2011 11:47am
You could create a function that totals the keys against quantity using a class selector. You would call the function when appropriate, such as a button click or onchange of the dropdown. You can use the val() function against select dropdowns and the parent function to find the corresponding quantity box for the multiplication. Make sure to parse the numeric values so the multiplication works out.

Leave a comment

To leave a comment, please log in / sign up