Reputation: 27
I have a page similar to what is below. When the user presses the submit button for the form, an API should be pinged, and if the GET request is unsuccessful, then the form should not submit. However, I'm finding that the GET request always fails, and the error message is blank. My guess is that the page is being redirected before the GET request has time to finish.
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://code.jquery.com/jquery-1.11.2.js" integrity="sha256-WMJwNbei5YnfOX5dfgVCS5C4waqvc+/0fV7W2uy3DyU=" crossorigin="anonymous"></script>
</head>
<body>
<form action="POST_URL" id="primary-form" method="POST">
<input type="submit" id="submit-button"/>
<input type="text" name="text-field" id="text-field">
</form>
<script>
$('#primary-form').submit(function(event) {
$.ajax({
type:"GET",
url: // API_URL //,
success: function(response) {
console.log("success");
console.log(response);
},
error: function(error) {
event.preventDefault();
console.log("error");
console.log(error);
},
});
})
</script>
</body>
</html>
I can modify the javascript as follows, in which case the GET request is successful. However, I don't know of a way to reverse the event.preventDefault()
<script>
$('#primary-form').submit(function(event) {
event.preventDefault();
$.ajax({
type:"GET",
url: // API_URL //,
success: function(response) {
console.log("success");
console.log(response);
// want to perform default action
},
error: function(error) {
console.log("error");
console.log(error);
},
});
})
</script>
Upvotes: 0
Views: 640
Reputation: 2311
One of the options is to store the result of the ajax call and retry the call if successful.
In the example below there's a success variable that is set to true when the call was successful and to false if it was not.
let success = false;
$('#primary-form').submit(function(event) {
console.log(success);
if (!success) {
event.preventDefault();
$.ajax({
type: "GET",
url: "https://httpbin.org/get",
success: function(response) {
success = true;
//submit the form again
$("#submit-button").click();
},
error: function(error) {
success = false;
console.log("error");
console.log(error);
},
});
}
})
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://code.jquery.com/jquery-1.11.2.js" integrity="sha256-WMJwNbei5YnfOX5dfgVCS5C4waqvc+/0fV7W2uy3DyU=" crossorigin="anonymous"></script>
</head>
<body>
<form action="POST_URL" id="primary-form" method="POST">
<input type="submit" id="submit-button" />
<input type="text" name="text-field" id="text-field">
</form>
</body>
</html>
Upvotes: 1
Reputation: 6598
You can unbind and then manually submit like this.
success: function(response) {
...
$('#primary-form').off('submit'); // unbind the javascript binding
event.currentTarget.submit(); // perform drfault functionality
},
Do not forget to unbind otherwise it will become a recursive call.
Upvotes: 1