jQuery - Ajax post request loads same page with form data added to URL
I think you should use <input type='button'>
instead <button>
and just use .click()
event of that <input type='button'>
as below.
Change
<button id="myButton">Register</button>
To
<input type='button' id='btnRegeister' value='Register'/>
And in JS
Change
$("#registerForm").submit(function()
To
$("#btnRegeister").click(function()
So your entire code become as below now ..
<form id="registerForm">
<input type="text" pattern="[A-Za-z]{1,20}" placeholder="First Name" name="guestFName" title="Up to 20 alphabetical characters" required>
<input type="text" pattern="[A-Za-z]{1,20}" placeholder="Last Name" name="guestLName" title="Up to 20 alphabetical characters" required>
<input type="email" placeholder="Email" name="guestEmail" title="Must be a valid email address" required>
<input type="text" pattern="08[36579]-\d{7}" placeholder="Phone Number" name="guestPhone" title="Must be an irish mobile number of format 08?-7 digits" required>
<input type="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,20}" placeholder="Password" name="guestPassword" title="Must be 8 or more characters long and contain at least one number and one uppercase letter" required>
<br>
<input type='button' id='btnRegeister' value='Register'/>
</form>
$(document).ready(function(){
$("#btnRegeister").click(function()
{
$.ajax(
{
url: "URL_GOES_HERE",
data: $('#registerForm').serialize(),
type: 'POST',
async: false
})
.done(function(response)
{
console.log(response);
var result = JSON.parse(response);
})
});
});
Try Above code, it is working for me
EDIT: You should include the 'type' attribute to your HTML:
<button type="submit" name="submit"></button>
Using the 'preventDefault' function will prevent the default form submit / redirect- This will stop the unintended behavior
$("#registerForm").submit(function(e)
{
e.preventDefault(); // Add this
$.ajax(
{
url: "URL_GOES_HERE",
data: $(this).serialize(),
type: 'POST',
async: false
})
.done(function(response)
{
console.log(response);
var result = JSON.parse(response);
})
});