Before submitting my form, I wan't to check if inserted dates are available. I have a php script which can perform this check and I want to call this php script via jquery/ajax.
I believe I should use event.preventDefault(); to avoid that the form is submitted. However I somehow cannot combine it with the Ajax call. The action of the form is performed anyway, the user is redirected to test.html.
What am I doing wrong? Anyone any suggestions?
My .html
<form id="checkData" action="test.html" method="post">
<input type="text" id="from" name="from">
<input type="text" id="to" name="to">
<input type="submit" value="Book">
My .js
$( "#checkData" ).submit(function( event ) {
var data = $("#checkData :input").serializeArray();
$.post("check.php", data, function(json){
if (json.status == "fail") { //this works fine without using the "event.preventDefault() statement"
event.preventDefault();
}
}, "json");
Put the preventDefault() on the click event of the submit button instead.
I didn't test the code so it might have some typo.
$( "#checkData input[type='submit']" ).click(function( event ) {
event.preventDefault();
var data = $("#checkData :input").serializeArray();
$.post("check.php", data, function(json){
if (json.status != "fail") {
$(#checkData).submit();
}
}, "json");
event.stopPropagation();
You can prevent the default behavior immediatelly.
Execute the post request.
If everything is ok, off the event submit and execute that the form submission programmatically.
if (json.status !== "fail") {
$self.off('submit', fn);
$self.submit();
}
This is the approach:
function fn(event) {
event.preventDefault();
var data = $("#checkData :input").serializeArray();
var $self = $(this);
$.post("check.php", data, function(json) {
if (json.status !== "fail") {
$self.off('submit', fn);
$self.submit();
}
}, "json");
}
$("#checkData").submit(fn);
Related
I am a little confused on how to take control of the submit event in a form, and I have tried to find a simple answer here.
I want to validate the form input before sending the form data to the form action scrip. I have tried to solve this by capturing the submit event, calling a validation script with Ajax, and if the validation succeeds I want the actual form procedure to be called. But I'm not sure how to proceed. Simply using location.replace("action.php") seems to fail (I guess that the form values aren't sent).
Here's the conceptual code:
$("form").on("submit", function(event) {
event.preventDefault();
data = {
the_input_val: $("#input_to_be_validated").val()
};
$.post("ajax_validate_input.php", data, function(data, status) {
if (status == "success") {
if (data == "invalid") {
alert("Invalid input");
// Form data is not sent... as expected
} else {
// Here I want to send the form data. But the event.preventDefault() prevents it from happening
// What do I put here to call the form's 'action' script with form data?
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="action.php">
<input id="input_to_be_validated" name="my_input" type="text">
<button type="submit" name="submit">Submit</button>
</form>
Call the submit() method on an HTMLFormElement to manually submit the form without passing through the submit event again.
The form can be retrieved by reading out the target property of the event object.
Though, to make this work, lose the name="submit" value on your button, as this will cause an error trying to submit with the method.
const $form = $("form");
$form.on("submit", function(event) {
event.preventDefault();
const data = {
the_input_val: $("#input_to_be_validated").val()
};
$.post("ajax_validate_input.php", data, function(data, status) {
if (status == "success") {
if (data == "invalid") {
alert("Invalid input");
// Form data is not sent... as expected
} else {
event.target.submit();
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="action.php">
<input id="input_to_be_validated" name="my_input" type="text">
<button type="submit">Submit</button>
</form>
You can use the submit() method like this:
if (status == "success") {
if (data == "invalid") {
alert("Invalid input");
// Form data is not sent... as expected
} else {
event.submit();
}
}
I have a form with the action attribute set to "/tasks/". All I want is that on submitting the form, the data go to "/tasks/", but the user is not redirected to "/tasks/", they just stay on "/" instead. Is it possible to achieve?
I tried to add "return false" and "preventDefault" to the "onclick" handler, but that's not what I need as they cancel the form submission.
<form id="add-task-form" method="POST" name="add-task-form" action="/tasks/" enctype="multipart/form-data">
<label for="name" class="field-description">*Name</label>
<input id="name" type="text"required name="name" autofocus="true"><br>
<label for="description-text" class="field-description">*Description</label>
<textarea id="description-text" name="description"></textarea><br>
<button type="submit" id="save-button" class="saveButton"><span>Add task</span></button>
</form>
$('#save-button').on( 'click', function(){
if($('input').data().length() != 0){
var data = $('#add-task-form form').serialize();
$.ajax({
method: "POST",
url: '/tasks/',
data: data,
success: function(response){
$('#add-task-form').css('display', 'none');
var task = {};
task.id = response;
var dataArray = $('#add-task-form form').serializeArray();
for(i in dataArray) {
task[dataArray[i]['name']] = dataArray[i]['value'];
}
appendTask(task);
getTasksCount();
}
});
return false;
$('#home-page').show();
$('#add-task-page').remove();
};
})
I'm new to js and jQuery and they are definitely not my strongest points, so please, advice.
It's shall work like this :
$('#save-button').click(function(event) {
event.preventDefault();
...
});
to know more about it : https://api.jquery.com/event.preventdefault/
You can do something like this.
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action','/tasks/'), $(this).serialize(), function(response){
// Do something
},'json');
return false;
});
});
quotation
if you want to prevent it all, you can use event.preventDefault(). But since you are using ajax and you don't want to reload the page, you can try to apply this code:
$("#save-button").click(function(){
$.post('{post_url}',
$("#add-task-form form").serializeArray(),
function(data){
if (data.success){
redirect = '{last}';
} else {
reload(true);
}
},"json"
);
});
I was trying to call jQuery.submit() function after ajax response. Where ajax response contains a form. But it couldn't call jQuery.submit() function when i submit the form without refresh.
I prepend the form with the existing code after successfull ajax response
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
},
error: function(data) {}
So after adding the form to the existing code. When i tried to submit the form it's got refresh instead of calling the function. How to make jQuery.submit() workable from ajax response?
$(".replyName").submit(function(event) {
alert(event.currentTarget[0].value);
});
You should place the submit event after you prepend the form. Because event's are only binded to the elements after the DOM is loaded.
And because the prepend the form dynamically, jQuery doesn't know which element it has to submit, because it didn't exist at the time it binded the event.
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
$( ".replyName").submit(function( event ) {
alert(event.currentTarget[0].value);
event.preventDefault();
});
},
error: function(data) {}
Since the form is not created in the document, you cant listen to submit event, unless you put the event listener after you prepend form into the dom
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
$(".replyName").submit(function(event) {
alert(event.currentTarget[0].value);
});
},
error: function(data) {}
You can also handle the event from body dom
$('body').on('submit', '.replyName', function(e){
// code here
});
There are two thing you can do:
Either you can rebind the click function like this:
success: function(data) {
event.preventDefault();
$(".name_wrapper").prepend('<form class="replyName"><textarea name="name" placeholder="Write your name"></textarea><button type="submit" class=" btn btn-primary">Reply your name</button></form>');
$('button').bind('click', function (event) {
event.preventDefault();
alert(event.currentTarget[0].value);
});
},
error: function(data) {}
or you can try this
$('button').on('click', function(e){
// code here
});
<form target="_blank" method="POST" action="somePage.php" id="myForm">
<input type="hidden" name="someName" value="toBeAssignedLater"/>
<button type="submit">Proceed</button>
</form>
At the beginning, the value of someName is not determined yet, I want to execute an Ajax to get and assign the value to it before the form is actually submitted.
I tried:
$("#myForm").submit(function (e) {
var $this = $(this);
someAjaxFunction(function (data) {
$this.find('input[name="someName"]').val(data.value);
});
});
But the form would have already submitted before the Ajax is finished, how can I ensure the form would be submitted after the Ajax is finished.
I want to keep the form submit event initiated by the user instead of code, such as $("#myForm").trigger('submit');, since I don't want the new window tab to be blocked by browsers.
$("#myForm").submit(function (e) {
var $this = $(this);
someAjaxFunction(function (data) {
$this.find('input[name="someName"]').val(data.value);
// submit form without triggering jquery handler
$this[0].submit();
});
// cancel the current submission
return false;
});
Why don't you ajax the value at page load and than submit the data?
$(function(){
someAjaxFunction(function (data) {
$('input[name="someName"]').val(data.value);
});
$("#myForm button").on('click',function(){
$(this).submit();
});
});
or place the ajax call on click event and submit whan the values is updated:
$(function(){
$("#myForm button").on('click',function(e){
e.preventDefault();
$.ajax({
url:url, //other params
success:function(data){
//thing to do before submit
$('input[name="someName"]').val(data.value);
$(this).submit();
}
});
});
});
The following code is intended to do a purely ajax POST request, instead it seems to do the POST via ajax and then the browser navigates to the response.
The HTML...
<div id="bin">
<form class="add" method="post" action="/bin/add/">
<p>I'm interested! Save for later.</p>
<input type="hidden" name="product_id" value="23423">
<input type="submit" value="Save">
</form>
<form style="display:none;" class="remove" method="post" action="/bin/remove/">
<p>I changed my mind--I'm not interested.</p>
<input type="hidden" name="product_id" value="23423">
<input type="submit" value="Unsave">
</form>
</div>
The jQuery...
$('#bin form').submit(function() {
$.post($(this).attr('action'),{
success: function(data) { $(this).hide().siblings('form').show() },
data: $(this).serialize()
});
return false;
})
As far as I understand it, the return false; line should mean that no matter what, any calls to the submit function or clicks on the 'Submit' button or the hitting of enter means that my function will execute and the browser will not navigate to /bin/add or /bin/remove. But for some reason, the browser is changing pages.
Any idea what I'm doing wrong here? Thanks.
It could be your JavaScript is failing, so the default behaviour is being executed.
Try to examine the XHR in a tool like Firebug.
Also, you could try event.preventDefault() (where the first argument to your event callback is event).
my bet it's because of the $(this), try it this way....
$('#bin form').submit(function() {
var $this = $(this);
$.post($this.attr('action'), {
success: function(data) {
$this.hide().siblings('form').show()
},
data: $this.serialize()
});
return false;
});
demo no error
demo with the error
Use event.preventDefault() to prevent the default action of the event. One benefit is that you can place this before the Ajax request, so that if it fails, you will still have prevented form submission.
Your code is failing because the value of this in your success callback is the global window object. Your attempt to hide it fails. You probably want this to refer to the form, like this:
$('#bin form').submit(function(ev) {
var _this = this;
ev.preventDefault();
$.post($(this).attr('action'), {
success: function() {
$(_this).hide().siblings('form').show();
},
data: $(this).serialize()
});
})
See a working example.
Is the $(...).submit(...) inside a $(document).ready(function(){ code here }); ?
should be like:
$(document).ready(function() {
$('#bin form').submit(function() {
$.post($(this).attr('action'), {
success: function(data) { $(this).hide().siblings('form').show(); },
data: $(this).serialize()
});
return false;
});
});