1

I have a file called try.php where there is code below having all javascript, PHP and html file in itself.

<?php if(isset($_POST["submit"])){ echo "hello"; } ?> <!DOCTYPE html> <html> <head> <title>Submit Form Using AJAX and jQuery</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> </head> <body> <form method="POST" id="myForm"> <input name="name" type="text" placeholder="Your Name"> <input name="email" type="text" placeholder="email"> <input name="submit" type="submit" value="Submit"> <div id="display"></div> </form> <script> $(document).ready(function(){ $("#myForm").submit(function(event) { event.preventDefault(); //prevent default action window.history.back(); var form_Data = $(this).serialize(); $.ajax({ type: "POST", url: "try.php", data: form_data, cache: false, success:function(response){ alert(response); } }); }); }); </script> </body> </html> 

The target of above code is just to submit form without reloading the page simply using AJAX and the form data should be handled by php here just echo "hello". The above code works fine it submits and php handles all properly but page is reloading. What should be the change in code?

4
  • Does this answer your question? Prevent page reload and redirect on form submit ajax/jquery Commented Mar 4, 2020 at 4:15
  • 1
    Yes, everything works fine in above code but I could not find why page is reloading? There is event.preventDefault(); to prevent the reloading. Commented Mar 4, 2020 at 4:16
  • 1
    why do you call window.history.back(); Commented Mar 4, 2020 at 4:18
  • Why window.history.back(); ?🤔 Commented Mar 4, 2020 at 4:19

1 Answer 1

1

Try this as javascript code

$(document).ready(function(){ $("#myForm").click(function(event) { event.preventDefault(); //prevent default action var form_Data = $(this).serialize(); $.ajax({ type: "POST", url: "try.php", data: form_Data, cache: false, success:function(){ alert("hello"); } }); }); }); 
Sign up to request clarification or add additional context in comments.

1 Comment

I recommend explaining where the problem was instead of simply pasting the correct code. This way more people can learn from the error.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.