I have a <form>:
<form method="post" action="">
<button type="submit" name="age" value="20">Age 20</button>
<button type="submit" name="age" value="30">Age 30</button>
</form>
When I am handling submission of this <form> with ajax like this:
$('form').submit(function (event) {
event.preventDefault();
$.ajax({
type : "POST",
cache : false,
url : $(this).attr('action'),
data : $(this).serialize(),
});
});
it completely ignores POST['age']. Is this intended behaviour or am I doing something wrong?
I've also tried <input type="submit" name="age" value="30" /> without luck.
As per the jQuery documentation for .serialize()...
Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button.
In other words, the button value will not be part of the POST array when the form is submitted with .ajax(). A regular "non-ajax" submit, however, WILL include the clicked button in the POST array.
A workaround would be to simply append the value of the button onto the serialized array...
$('button').on('click', function (event) {
event.preventDefault();
$.ajax({
type : "POST",
cache : false,
url : $(this).parent('form').attr('action'),
data : $(this).parent('form').serialize() + '&' + $(this).attr('name') + '=' + $(this).val(),
});
});
Note that I'm using the click event of the button, rather than the submit event of the form, so that I can easily capture which button was used.
DEMO: http://jsfiddle.net/ty7c5k9b/
Related
After changing my button type to submit it's not submitting the form. Somehow, the AJAX request is not working after that. If I change it to type="button" then it's working, but I want this because required validation is not working while giving type="button". It only works when I'm giving button type submit but then the form is not submitting.
<form>
<input type="email" class="form-control" id="passwordReset" placeholder="Email" required/>
<button type="submit" id="passwordButton"> Submit</button>
</form>
$("#passwordButton").on('submit', function(e) {
e.preventDefault();
const email = $("#passwordReset").val();
$.ajax({
type: "GET",
url: "/forget_password=" + email,
success: function(response) {
if (!response.data) {
$(".sendError").show();
} else {
$(".sendSuccess").show();
}
}
});
})
I want my form to be submitted while checking the required condition also.
Quoting from MDN:
Note that the submit event fires on the element itself, and not on any or inside it. (Forms are submitted, not buttons.)
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event
Attach the listener to the click even of the button, or to the submit event of the form.
HTMLFormElement: submit event
Note that the submit event fires on the <form> element itself, and not on any <button> or <input type="submit"> inside it. (Forms are submitted, not buttons.)
Try click event instead:
$("#passwordButton").on('click', function(e) {
Update: I think simply submit event on the form is enough here as the event will fire on clicking any input type=submit:
$('#myForm').on('submit', function(){
alert('Your form is submitting');
/*
Your code here
*/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
<input type="email" class="form-control" id="passwordReset" placeholder="Email" required/>
<button type="submit" id="passwordButton"> Submit</button>
</form>
I think you should just create a normal like <button onclick="Submit()">save</button>
and write Code like that:
Submit(e){
e.preventDefault();
const email = $("#passwordReset").val();
$.ajax({
type: "GET",
url: "/forget_password=" + email,
success: function(response) {
if (!response.data) {
$(".sendError").show();
} else {
$(".sendSuccess").show();
}
}
});
})
}
Add Id or class attribute to your form.
<form id="formYouWantToSubmit">
<input type="email" class="form-control" id="passwordReset" placeholder="Email" required/>
<button type="submit" id="passwordButton"> Submit</button>
</form>
Then,
$("#formYouWantToSubmit").on('submit', function(e) {
const email = $("#passwordReset").val();
// This will validate if email having any value (from string point of view)
if (!email) {
e.preventDefault();// To restrict form submission
//### Do anything here when validation fails
return false;
}
$.ajax({
type: "GET",
url: "/forget_password=" + email,
success: function(response) {
if (!response.data) {
$(".sendError").show();
} else {
$(".sendSuccess").show();
}
}
});
})
Things to remember:
button type submit will ultimately submits the form to current page (due to action attribute is missing)
When we user Ajax to do something we ultimately seek a 'page-load-less' activity. In your case you are doing both submitting the form using submit button and making Ajax request, which will hard to get executed and if any chance it gets executed you won't be able witness any 'success' or 'error' activities because until then page already been reloaded.
I have a form on a page.
<div id="form_catch">
<form id="form2">
<div><input type="button" value="Dear Diary" id="add" /><input type="button"
value="Dear Friend" id="add_1" /></div>
<div><input type="text" id="salutations" name="salutations" value=""/></div>
<input type="submit" value="Submit" class="submit" />
</form>
</div>
I use a javascript to manipulate this form
$(document).ready(function(){
var form_box_copy = $('#form_catch').html()
$("#add").click(function(){
$('input#salutations').val('Dear Diary,');});
$("#add_1").click(function(){
$('input#salutations').val('Dear Friend,');});
//console.log('test button');
$("form#form2").submit(function(evt){
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://wei.rocks/test2.html',
type: 'GET',
data: {
format: 'html'
},
enctype: 'multipart/form-data',
processData: false,
error: function(){alert('You Failed');},
success: function (response) {
alert('You passed');
$('#form_catch').html(form_box_copy + "html replaced");
$('#form_catch').append("Test222222222");}
});
return false;
})
})
When I run the page the scrip works as designed I ajax the form, the task are successful. After success It replaces the form with a fresh copy of it self. All this work except when it is complete the Replacement of the form is no long working with the Java script.
The reason this is happening is because when you replace the form with the new html, it discards the submit event registration attached to the form.
To bypass it you can either re-register the event or, as a better approach, register the event at the document level.
Simply change:
$("form#form2").submit(function(evt){
// your code
});
to:
$(document).on('submit', '#form2', function(evt) {
// your code
});
});
This should now work since the event is registered at the document level and not at the form level (and the document is never being replaced).
In general if you are replacing DOM elements, then the events registered to them will no longer work. This is why registering to the element's parent is a better approach (when needed).
See this codepen for working example.
Hope this helps.
I want to insert an email address into my db with an ajax call.
Here comes the problem. Instead of working into the background, it refreshes the page.
alert("yea"); in the success function is not being reached.
What could be the problem?
$(document).ready(function() {
$("#header-subscribe").click(function(){
var str = $("#email").val();
if( validateEmail(str)) {
$.ajax({
url: 'php/signupForm.php',
type: 'GET',
data: 'email='+str,
success: function(data) {
//called when successful
alert("yea");
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
The form:
<form id="hero-subscribe" class="the-subscribe-form" >
<div class="input-group">
<input type="email" class="form-control" placeholder="Enter Your Email" id="email">
<span class="input-group-btn">
<button class="btn btn-subscribe" id="header-subscribe" type="submit">subscribe</button>
</span>
</div>
</form>
The Ajax call has nothing to do with the refresh. You have a submit button and the purpose of the submit button is to submit the form.
The simplest solution would be to not use a submit button:
type="button"
However, binding the event handler to the click event of the button is not good practice. So instead of that and changing the type, bind the handler to the submit event and prevent the default action (which is submitting the form):
$("#hero-subscribe").submit(function(event) {
event.preventDefault();
// ...
});
You need to prevent the default action of the click...
$("#header-subscribe").click(function(event){
event.preventDefault();
You should bind the submit event of form and use event.preventDefault() to prevent the default action of event.
$("#hero-subscribe").submit(function(event) {
event.preventDefault();
//Your code
});
event.preventDefault() the form action, otherwise it submits like a normal form.
$("#header-subscribe").click(function(event){
event.preventDefault(); //stop the default submit action
I've got the following form:
<div>
<form name="ajaxformname" id="ajaxform" action="/request" method="POST">
AJAX:
<input id="btn1" name="feeling" type="submit" value="Fine">
<input id="btn2" name="feeling" type="submit" value="Neutral">
<input id="btn3" name="feeling" type="submit" value="Bad">
</form>
</div>
which should be posted to a server via ajax.
Here is the associated javascript:
$('#ajaxform').submit(function (event) {
event.preventDefault();
var form = $(this);
var action = form.attr("action"),
method = form.attr("method"),
data = form.attr("value");
$.ajax({
url: "/request",
type: method,
data: data
});
Now - depending on which of the three buttons has been clicked - I want their values to be posted to the server. But form.attr("value") just gives me the value of the form but not of the input field.
Any suggestions? A solution would be to create the different forms but that doesn't seems to be DRY ...
First thing, if you wanna use the action attribute of the form, you should reference it in the url param of ajax request:
url: form.attr('action'),
Now, for the button clicked, you should use this (it's a workaround because submit buttons are not incluided in the form serialization, if not, I would use it instead):
$(function () {
//When any of the buttons is clicked, we store in the form data the clicked button value
$('#ajaxform').on('click', 'input[type=submit][name=feeling]', function(e) {
$(this.form).data('clicked', this.value);
});
$('#ajaxform').submit(function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr("method"),
data: { clickedButton : form.data('clicked') } //Retrieve the button clicked value from the form data
});
});
});
Here the working example: https://jsfiddle.net/68qLxLgm/1/
Hi kindly use the following to get the id of the button that has been clicked
$("input").click(function(e){
var idClicked = e.target.id;
});
I am trying to add product in to the cart using jQuery and AJAX. The situation is that I am getting more then 30 forms that are generated dynamically using foreach loop. after page loading i get product list but need to add only one product in to the cart , and dont want reload the page , so i am using AJAX. please help me how can i achieve this.
Most important thing is when i tried without <form> tag , the value of productId always goes 1 because its the first value of id attribute, and saves product in to the cart whose id is one. So I am using <form>.
this is code (its a sample code) :
<form id="addToCartForm" action="" method="post">
<input type="hidden" id="productId" value="${products.productid}">
<button id="btnSubmit">Add to Cart</button>
</form>
<form id="addToCartForm" action="" method="post">
<input type="hidden" id="productId" value="${products.productid}">
<button id="btnSubmit">Add to Cart</button>
</form>
<form id="addToCartForm" action="" method="post">
<input type="hidden" id="productId" value="${products.productid}">
<button id="btnSubmit">Add to Cart</button>
</form>
I already tried lots of things, like jquery.form.min.js, but nothing is going on as according just i like want.
please help. thnx in advance.
Edited
script.js:
$(document).ready(function(){
$(".addToCart").click(function(){
$.post('addToCart.htm', {productId: $('input[type=hidden]#productIdId').val()},
function(message){
$("#message").html(message);
}
);
});
});
You are looking for something like:
$(document).on('click', '#btnSubmit', function(){
var value = $(this).prev().val();
$.ajax({
url: 'path/to/server/script',
type: 'post',
data: { productid: value },
success: function(){
alert('succeeded');
}
});
});
Anyway, you have to use classes instead ids if you have same kind elements. An id is an identifier, so it must to be unique.
You could do something like this:
$("#addToCartForm").on("submit", function(e) {
var $form = $(this);
e.preventDefault();
e.stopPropagation();
$.ajax({
method: "POST",
action: $form.attr("action"),
data: $form.serialize()
}).done(function() {
...
});
});
UPDATE: Oh! and yeah, the IDs of your forms should be unique.
UPDATE 2: Without forms
<a class="addToCart" href="#" data-productid="${products.productid}">Add to Cart</a>
JavaScript:
$(".addToCart").on("click", function(e) {
e.preventDefault();
e.stopPropagation();
$.ajaxPost({
action: "addToCart.html",
data: {productId: $(this).data("productid")}
}).done(function() {
...
});
});