• How to submit Form without refreshing page using JQuery and Json combination

    Use jQuery + JSON combination to submit a form without refreshing page like this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    
    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'>Result comes here..</div>
     
    _test.php:
     
    <?php
          $arr = array( 'testDiv' => $_POST['txt'] );
          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;
        });
     
    });<script type="text/javascript" src="jquery-1.4.2.js"></script><script type="text/javascript" src="jsFile.js"></script>
    Result comes here..
    Tags: , ,

Comments on this post

Leave a Reply

  • Security Code :


    − 4 = three