Posted by : Anjana Jayaweera Sunday, November 10, 2013

We can submit a form via jQuery, AJAX and PHP from two methods.
1. Data String
2. JSON

Here, Im using the 1st method and it is the easiest.


// link jquery main

$(function() {

// Your Button ID

$("#submit").click(function() {
 
      /* field names */
      var fld1 = $("#fld1").val();
      var fld2 = $("#fld2").val();
      var fld3 = $("#fld3").attr('checked');
      var fld4 = $("fld4 :selected").val(); 

      var dataString = 'fld1=' + fld1 + '&fld2=' + fld2 + '&fld3=' + fld3 + '&fld4=' + fld4 ;
      //alert (dataString);return false;
        
        $.ajax({
          type: "POST",
          url: "./form-submit.php",
          data: dataString,
          success: function(html) {
             var trimmed = trim(html); 
             if(trimmed == 'success') {
                /* Do what you want to do when its success */
            } else {
                /* Error Message */
            }
          }
        });
        return false; 
    });
});



Here I used a very simple method to post data into PHP. Now lets look at the "form-submit" file

$fld1 = $_REQUEST['fld1'];
$fld2 = $_REQUEST['fld2'];
$fld3 = $_REQUEST['fld3'];
$fld4 = $_REQUEST['fld4'];


/* MySQL Insert commands. At the end, echo "success"; */

echo "success";

Why echo Success?
That is the command we are giving for jQuery file saying that the operation did successfully. If form-submit returned a string different than 'success', then its an error.

PS : in jQuery file, i commented "alert (dataString);return false;". You can uncomment this and see whether your dataString is correctly passing or not. coz of return "false", it will not proceed to ajax call. :)

On a later day, lets see how to achieve this via JSON. :)

Leave a Reply

Subscribe to Posts | Subscribe to Comments

Popular Post

Blogger templates

Labels

- Copyright © My Code Genius by 2 Geniuses -Metrominimalist- Powered by Blogger - Designed by Johanes Djogan -