Wednesday, October 13, 2010

Post entire form and return JSON data from PHP


Here is the entire code that will post entire PHP
form to the target page. The target page will receive
the post data and return the result in the format of JSON data.

Here are the two things one is it will send entire form data,
so you not need to mention every control name with parameter in Ajax.
second one is the target page which receive the data, is return output as
JSON Format.

First you need to download the latest jquery from the jquery site and then copy and
paste the below code and run it.

===========================================================
[1] email-form.php
------------------------------------
<script type="text/javascript" src="jquery-1.6.js"></script>
<form id="emailForm">
<p>Name:<br />
<input id="nName" type="text" name="nName"/></p>
<p>E-mail:><br />
<input id="email" type="text" name="email"/></p>
<p><input type="submit" value="Submit" /></p>
<div id="msg"></div>
</form>
<script type="text/javascript">
$(function(){
    $("#emailForm").submit(function(){
        dataString = $("#emailForm").serialize();
        $.ajax({
        type: "POST",
        url: "email-form-process.php",
        data: dataString,
        dataType: "json",
        timeout: 5000,
        error: function (xhr, err) {
                $("#msg").html(xhr.responseText + xhr.readyState + xhr.status);
            },
        success: function(data) {
            $("#msg").html("Hi " + data.nName + ", your email is " + data.email);
        }
    });
    return false;           
});
});
</script>

===========================================================
[2] email-form-process.php
------------------------------------
<?php
$retArr = array();
$retArr["nName"] = $_POST['nName'];
$retArr["email"] = $_POST['email'];
echo json_encode($retArr);
?>

===========================================================

4 comments:

  1. Very informative. Will this AJAX post work when there is input type FILE on form?

    ReplyDelete
  2. Pankaj, I have not tried it with input type FILE... I will test it and let you know about it.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Hi Amit, Article is very useful, Do you have any sample of a form that submit value into a mysql database at the same time sending the details as an email also using json ? Thanks in advance

    ReplyDelete