Home » Php » php – Server response is printed on the browser but not returned to success function in ajax

php – Server response is printed on the browser but not returned to success function in ajax

Posted by: admin February 25, 2020 Leave a comment

Questions:

I am not able to get the response to ajax success call back function. The response form the server is being directly printed on the browser

<body>
    <script>
      $(document).ready(function() {
        $.ajax({
          url: $("#form").attr("action"),
          type: "POST",
          data: $("#form").serialize(),
          success: function(data) {
            alert(data);
          }
        });
      });
    </script>
    <form action="a.php" method="post" id="form">
      <input type="text" name="name" id="name" placeholder="name" />
      <input type="submit" value="submit" />
    </form>
  </body>

my php code

<?php
    echo 'hii';
?>
How to&Answers:

Can you Replace AJAX script below mentioned.

<form method="post" id="form">
  <input type="text" name="name" id="name" placeholder="name" />
  <input type="submit" value="submit" />
</form>

 $("#form").submit(function(e) {

    e.preventDefault(); // avoid to execute the actual submit of the form.

    var form = $(this);
    var url = form.attr('action');

    $.ajax({
           type: "POST",
           url: 'a.php',
           data: form.serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });
});