Skip to content Skip to sidebar Skip to footer

Easiest Way To Make A Form Submit Without Refresh

I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit

Solution 1:

Use jQuery + JSON combination to submit a form something like this:

test.php:

<scripttype="text/javascript"src="jquery-1.4.2.js"></script><scripttype="text/javascript"src="jsFile.js"></script><formaction='_test.php'method='post'class='ajaxform'><inputtype='text'name='txt'value='Test Text'><inputtype='submit'value='submit'></form><divid='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] );
                        }
                      }
        });

        returnfalse;
    });

});

Solution 2:

The best way to do this is with Ajax and jQuery

after you have include your jQuery library in your head, use something like the following

$('#someForm').submit(function(){
   var form = $(this);

   var serialized = form.serialize();

   $.post('ajax/register.php',{payload:serialized},function(response){
       //response is the result from the server.if(response)
       {
           //Place the response after the form and remove the form.
           form.after(response).remove();
       }
   });
   //Return false to prevent the page from changing.returnfalse;
});

Your php would be like so.

<?phpif($_POST)
    {
       /*
           Process data...
       */if($registration_ok)
       {
           echo'<div class="success">Thankyou</a>';
           die();
       }
    }
?>

Solution 3:

I use a new window. On saving I open a new window which handles the saving and closes onload.

window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');

The php file would contain a bodytag with onload="window.close();" and before that, the PHP script to save the contents of my editor.

Its probably not very secure, but its simple as you requested. The editor gets to keep its undo-information etc.

Post a Comment for "Easiest Way To Make A Form Submit Without Refresh"