简体   繁体   中英

Submit Form Without Reloading Page and Get Output [PHP, jQuery]

Hellow, I've been trying to submit a form without reloading and getting PHP output on the same page. The main objective is to submit the form values to a PHP file and get the output sent by the PHP file. To understand it better, let's take a look on following code snippet: HTML & jQuery Code:

<html>
  <head>
    <script src="//code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('form').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            type: 'post',
            url: 'on.php',
            data: $('form').serialize(),
            success: function () {
              alert('form was submitted');
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form>
      <input id="name" name="name"><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

PHP Code:

<?php
if (isset($_POST['submit'])){
$name=$_POST['name'];
if($name == 'Johny'){
    echo "Welcome Johny";
}
else{
echo "I Dont Know You";
}
}
?>

What I Want:

  • When user enter value in the Input box and submit it, the page should display output value eg ECHO value without reloading the webpage.

To be more specific on my first comment, you have to put an exit statement after you echo the response so the rest of the code doesn't execute, also to check whether the form was sent or not you can add a hidden input in your form with the value "1" ( <input name="formSent" type="hidden" value="1"> ) that gets checked in your PHP :

<?php
if (isset($_POST['formSent'])){
$name=$_POST['name'];
if($name == 'Johny'){
  echo "Welcome Johny";
  exit;
}
else{
  echo "I Dont Know You";
  exit;
}
}
?>

and then get the response from the ajax request in the success's callback parameter, also specify the method: 'POST' because jQuery's $.ajax function uses the method GET by default:

<script>
  $(function () {

    $('form').on('submit', function (e) {

      e.preventDefault();

      $.ajax({
        type: 'post',
        url: 'on.php',
        method: 'POST',
        data: $('form').serialize(),
        success: function (message) {
          alert(message);
        }
      });

    });

  });
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM