The easiest way to make a request without updating

I am trying to create a simple calculator. Using PHP, I managed to get the values ​​from the input fields and go from the POST menu, but, of course, the form is updated after submitting.

Using Javascript, I tried using

function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'

but this would continue to give a β€œ0” response after the button was clicked because it could not get the values ​​from the POST since the form was not submitted.

So, I'm trying to solve either the easiest way to do this via ajax, or something like that

or get the selected values ​​in the navigation menu using JavaScript.

I read a few ajax examples on the internet, but they are quite confusing (not familiar with the language)

+5
source share
3 answers

Use the jQuery + JSON combination to submit the form 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'>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;
    });

});
+7
source

The best way to do this is with Ajax and jQuery

after you include jQuery in your library, 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.
   return false;
});

Your php will be like that.

<?php
    if($_POST)
    {
       /*
           Process data...
       */


       if($registration_ok)
       {
           echo '<div class="success">Thankyou</a>';
           die();
       }
    }
?>
+7
source

. , .

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

php bodytag onload = "window.close();" PHP script .

, , , . ..

0

All Articles