How am I able to prevent the page from refreshing when submitting a form? I want to be able to click submit, but not refresh the page and just return a message under the button saying "Thanks for taking the survey! We'll be sure to reach out to you."
I read some articles and questions around saying, best way is to achieve it is through AJAX? Was hoping if there is another way to do so, but if AJAX is the only way, is there a code that it is easy to understand what it does.
Thank you all so much!
CodePudding user response:
PHP is a language that sits server side. Sending a form happens in the browser, thus client side. The browser is responsible handling the behaviour. By default, html sends the requests via post or get to the endpoint defined in the form "action".
If you want to dynamically send a form without a hard reload, there is no way in PHP, as you need to talk to the browser.
The fast forward way of doing this would be using a library like jQuery on the front-end.
I suggest to leave the action to be working with a redirect to have a fallback for browsers without JS.
Coming from a dummy form:
<form id="target" action="destination.html">
<input type="text" name="hello" value="Hello there">
<input type="text" name="user" value="Username">
<input type="submit" value="Go">
</form>
you can prevent the default behaviour with javascript/jquery easily:
$( "#target" ).submit(function( event ) {
event.preventDefault();
});
This prevents the form from sending and redirecting. you can now use Javascript to send the data and update the dom based on the response:
$( "#target" ).submit(function( event ) {
event.preventDefault();
/*
make your data requests, formats and more here.
then send the data in the "data" part
*/
$.ajax({
type: "POST",
url: url,
data: {"name": hello, },
success: mycallback,
dataType: dataType
});
});
"success" points at a callback function defined elsewhere. you can find all properties of that function at https://api.jquery.com/jquery.post/
CodePudding user response:
You can you this simple code
step 1: Create form
step 2 : Handle form submission in query
step 3 : e.preventDefault(); this will help to prevent from reload
step 4 : you can change test.php with your actual url
<html>
<head>
<title>Test Form</title>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
</head>
<body>
<form action="#" id="login_form" method="post">
<input type="email" name="email_id" id="email_id" value="[email protected]" placeholder="Email">
<button type="submit" >Sign In</button>
</form>
</body>
</html>
<script type="text/javascript">
$( "#login_form" ).on( "submit", function(e) {
var dataString = $(this).serialize();
// alert(dataString); return false;
$.ajax({
type: "POST",
url: "test.php",
data: dataString,
success: function (data) {
alert("Submit");
}
});
e.preventDefault();
})
</script>