Jquery, Ajax forms, PHP and Mysql at the table

3 11 2008

Before starting, if you have PHP.x < PHP.2, you need to put into your includes folder the library jsonwrapper (this encodes/decodes json objects).

Imagine you have a form to add an item to a shop and you want to create a new category for that shop without leaving that page.

One way to do it is to have a link “add a new category” that when clicked, shows some input fields for adding the new category (e.g. name and description) and a button to submit these data.

When the button is clicked, javascript detects that you do not want to send the whole form, but instead it retrieves these fields and sends them as an Ajax request to the server. The php code on the server side will get the data, perform the request (adding the category) and return some data (e.g. the new category object) to the form. Javascript waits for the response and processes it.

This is the general idea, now let’s have a look at the code:

Client-side: form.php

in the HEAD insert javascript:

<script language="javascript" type="text/javascript" src="/assets/inc/jquery.js"></script>

<script language="javascript" type="text/javascript">
$(document).ready(function(){
$("ul#add-category-fields").hide();
$("a#add-category").click(function(){
     // Show subform to add a new category
     $("ul#add-category-fields").show();
     return false;
    });

    $("#btn-add-category").click(function(){
        $("#action").val("add category");
        $("#fm_edit").submit();
    });

    $("#fm_edit").submit(function(){
        if($("#action").val()=="add category")
        {
            //data to send
            var data={'catname': $("#catname").val(),'catdescription':$("#catdescription").val(),'add': "add"};
               $.post("manage_category.php",data, function(data) {
               if(data.idshopcategory>0)
               {
                    $("new category has been added").insertAfter("a#add-category");
                    $("ul#add-category-fields").hide();//hide again the fields
               }else $("<br><p class='alert'>something went wrong, category could not be added, try adding the new category from the Categories menu.</p>").insertAfter("a#add-category");
               },"json");//end post
               $("#action").val("");
               return false;
        }else{
           //send to this page for edit item processing
            $("#action").val("");
           return true;
        }
   });
});//end document ready
</script>

The first line imports jquery library

The second script tag includes Ajax interaction:

it dynamically displays the fields in the form that will be sent as Ajax (hidden at the beginning) and when submitted it discriminates between the whole form and the sending of these fields (’action’).

it retrieves those fields within the form whose values we want to send to the server and encodes them as a json object.

it  sends a simple POST request to a server with the data as json.

it handles the response by veryifing the data sent back by the server. If successful, it modifies the form and add a positive feedback, otherwise it shows a negative feedback.

in the BODY:

within the HTML form

....
 <input type="hidden" id="action" name="action" value="">
.....

<a href="#" id="add-category">add a new category</a>
   <ul id="add-category-fields">
        <li><label for="catname"></label> <input type="text" id="catname" name="catname" value=""></li>
        <li><label for="catdescription"></label> <input type="text" id="catdescription" name="catdescription" value=""></li>
        <li><input type="button" name="add category" id="btn-add-category" value="Add category"></li>
  </ul>

Server-side: manage_data.php

PHP code:

<?php
//initialise vars
$new_record_id=0;$name="";$description="";
//json object returned to the calling page
$foo= array(
  'idshopcategory'  =>0,
  'catname'   =>0,
);

require_once incpath("/jsonwrapper/jsonwrapper.php"); //encode/decode json objects for AJAX calls
//get the data from the post request sent through javascript
if(!empty($_POST["add"])){

$name=$_POST['catname'];
$description=$_POST['catdescription'];
$new_record_id= $ShopCategory->newRecord($data);
}

 //json object returned to the calling page
$foo= array(
 'idshopcategory'  =>1,
 'catname'   =>$name,
'catdescription'   =>$description,
);
// Now encode the array to JSON format
$json = json_encode($foo);
// encode array $json to JSON string
echo $json;
die();
?>

it creates an array of values to be returned

it encodes them as a json object (using json_encode as defined in the library jsonwrapper)

it sends the object to the page form.php.


Actions

Information

Leave a comment