tags:

views:

41

answers:

1

Can someone show me a tutorial of using jquery to display successful form submission without refreshing the page. Something like that happens on gmail when a message is delivered and the yellow overlay that shows that you message was delivered and then fade outs.

+2  A: 

Use jQuery+JSON combination something like this:

test.php:

<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>

<form action='_test.php' method='post' class='ajaxform'>
 <input type='text' name='txt' value='Test Text'>
 <input type='submit' value='submit'>
</form>

<div id='testDiv'></div>

_test.php:

<?php
      // Code here to deal with your form submitted data.
      $arr = array( 'testDiv' => 'Form is successfully submitted.' );
      echo json_encode( $arr );
?>

jsFile.js:

jQuery(document).ready(function(){

    jQuery('.ajaxform').submit( function() {

        $.ajax({
            url     : $(this).attr('action'),
            type    : $(this).attr('method'),
            dataType: 'json',
            data    : $(this).serialize(),
            success : function( data ) {
                        for(var id in data) {
                            jQuery('#' + id).html( data[id] );
                        }
                      }
        });

        return false;
    });

});




OR:

You can use jQuery Form Plugin

NAVEED
@naveed : this above code was working fine yesterday but today smthing strange is happening. Instead of adding the content of **testDiv** along with the content of the page now its going to test.php and showing {testdiv => "delivered" } in an empty page.
Ayush
@Ayush: What did you change in yesterday's code. It is showing JSON data(`{testdiv => "delivered" }`) in empty page because of the following possible reasons: **1.** May be your jQuery function is not called because you have removed the `class='ajaxform'` from `form` tag which is used to capture submit event in jQuery code. **2.** May be you have change the selector(`.ajaxform`) in `jQuery('.ajaxform').submit(.....)`. **3.** May be you jQuery code/file is not included properly.
NAVEED
when i check using firebug it shows me - POST http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php 404 Not Found 1.26s jquery.min.js (line 130) i have checked that the address of sms.php is correct
Ayush