Submit form without form id - javascript

I need to submit form using through Ajax call but I'm having trouble selecting the form. I don't want to use form ID because I'm having multiple forms and I need to setup one code for all
$(".pay").on("click",function(){
var form = $(this).closest(".card-body").find("form");
//$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {
})
//});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card" >
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body" >
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline" >decline</button>
</div>
</div>

No need to add form submit code because you are preventing submit, so when will you click just fetch data from the form and call your AJAX service.
I added one console log where you can see your form data.
$(".pay").on("click",function(){
var form = $(this).closest(".card-body").find("form");
var formData = $(form).serialize();
console.log(formData);
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body" >
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline" >decline</button>
</div>
</div>

This will help you to reduce duplicating the code..
$(document).ready(function() {
$('form').on('submit', function(e){
e.preventDefault();
Var action = $(this).action;
Var method = $(this).method;
Var data = $(this).serialize();
// perform ajax operation here with data, action and method
});
});
Happy coding :)

Your code is creating submit handler everytime the button is clicked, all you want is to send ajax call onclick, so just do that part.
$(".pay").on("click",function(){
var form = $(this).closest(".card-body").find("form");
// below code is creating submit handler everytime the button is clicked
$(form).submit(function(e) {
e.preventDefault();
var formData = $(form).serialize();
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {
})
});
});
Also .find returns jQuery object, no need to make it Jquery object again, simple form will do instead of $(form).. rather declare like var $form = $(this).closest(".card-body").find("form")
Something like below, try
$(".pay").on("click",function(){
var $form = $(this).closest(".card-body").find("form");
e.preventDefault();
var formData = $form.serialize();
submitForm(formData);
});
function submitForm(formData){
$.ajax({
type: 'POST',
url : "php/pay.php",
data: formData
})
.done(function(response) {
})
}
I've created below sample to refer
$(function() {
$(".pay").on("click", function(e) {
var $form = $(this).closest(".card-body").find("form");
e.preventDefault();
var formData = $form.serialize();
console.log(formData)
submitForm(formData);
});
function submitForm(formData) {
alert("submitting form with " + formData)
$.ajax({
type: 'POST',
url: "php/pay.php",
data: formData
})
.done(function(response) {})
}
});
.card {
width: 50%;
float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
<div class="card-header">
<h1>XXX</h1>
</div>
<div class="card-body">
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline">decline</button>
</div>
</div>
<div class="card">
<div class="card-header">
<h1>YYY</h1>
</div>
<div class="card-body">
<form>
<input name="user2" value="mat2" type="hidden">
<input name="id2" value="122" type="hidden">
</form>
<button class="btn btn-success pay" value="pay">pay2</button>
<button class="btn btn-danger decline" value="decline">decline2</button>
</div>
</div>

Erm.. Why not just put the two buttons inside the form, to avoid any confusion or off-chance that the script might trigger another one of the "multiple forms" and refer to the nameless form through the parent element instead, like?
html:
<form>
<input name="user" value="mat" type="hidden">
<input name="id" value="12" type="hidden">
<button class="btn btn-success pay" value="pay">pay</button>
<button class="btn btn-danger decline" value="decline">decline</button>
</form>
script:
$(function() {
$(".pay").on("click", function(e) {
var $form = $(this).parent();
e.preventDefault();
var formData = $form.serialize();
submitForm(formData);
});

Related

Javascript - After creating a div, Ajax is not working

I have a button for a form. When I click the button, the form is created. After being created, the form is not working with Ajax. My script codes are in here. My #testform is not wrong because it's working without creating form. Do you have any ideas?
function addDiv() {
var panel = document.querySelector(".add_new");
var div = document.createElement("div");
div.innerHTML = '<br> <form id="testform" method="POST"> <div class="row" style="padding-left:10rem;"> <div class="col-md-4"> <input type="text" class="form-control" value="" placeholder="Başlık" name="yeniBaslik" required></div> <div class="col-md-4"> <input type="text" placeholder="Açıklama" name="yeniAciklama" class="form-control" value="" name="" required> </div> <div class="col-md-2 text-left"> <button type="submit" class="btn btn-success btn-animated btn-wide addToDatabase">Add to the Database</button> </div> </row> </form> <br>';
panel.appendChild(div);
}
$("#testform").submit(function(e) {
e.preventDefault();
var formData = new FormData($("#testform").get(0));
$.ajax({
url: 'config.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function() {
setTimeout(
function() {
$(".addToDatabase").html("Successfully.");
}, 1000);
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addDiv()"> Create a form </button>
<div class="add_new"></div>
Since second statement is executed before "div" is created, submit event is not being listened to on the new <form>
function addDiv() {
/*...*/
panel.appendChild(div);
$("#testform").submit(function(e) { /*...*/ });
}

Javascript - one button call ajax and one button submit form using html5 form validation

I have a form that I want to use the required attribute, which I believe is from html5 to make sure the user puts in a name before running the ajax to send and email and stays on this page (index.php). The form below works. My problem is that I can't figure out how to a a button called pay that submits the form to pay.php like a regular form submit so the user ends up on pay.php when they click "pay" and I want the form validation to still occur when they click pay and on pay.php I can grab the contactName from the post.
<form id="contactForm" method="post" class="tm-contact-form">
Name: <input type="text" id="contactName" name="contactName" class="form-control" placeholder="Name" required/>
<button type="submit" id="inquire-button" class="btn btn-primary">Inquire</button>
<div id="mail-status"> </div>
</form>
<script type="text/javascript">
$("inquire-button").on('click',function(e){
e.preventDefault();
});
$("#contactForm").on('submit',function(e){
sendContact();
e.preventDefault();
});
function sendContact() {
jQuery.ajax({
url: "mailer.php",
data:'contactName='+$("#contactName").val(),
type: "POST",
success:function(data){
$("#mail-status").html(data);
},
error:function (){}
});
}
</script>
EITHER don't use the click, but only the submit event
$("#contactForm").on('submit', function(e) {
const $btn = $(document.activeElement);
if ($btn.is("#inquire")) {
console.log("Inquire clicked")
e.preventDefault();
jQuery.ajax({
url: "mailer.php",
data: 'contactName=' + $("#contactName").val(),
type: "POST",
success: function(data) {
$("#mail-status").html(data);
},
error: function() {}
});
}
else console.log("Pay clicked")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="contactForm" method="post" class="tm-contact-form">
Name: <input type="text" id="contactName" name="contactName" class="form-control" placeholder="Name" required/>
<button type="submit" id="inquire-button" class="btn btn-primary">Inquire</button>
<button type="submit" id="pay" class="btn btn-primary">Pay</button>
<div id="mail-status"> </div>
</form>
OR use a button
$("#contactForm").on('submit', function(e) {
console.log("Submitted (pay)")
})
$("#inquire-button").on("click", function() {
if (!this.form.checkValidity()) {
this.form.reportValidity()
return
}
console.log("Inquire clicked")
jQuery.ajax({
url: "mailer.php",
data: 'contactName=' + $("#contactName").val(),
type: "POST",
success: function(data) {
$("#mail-status").html(data);
},
error: function() {}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="contactForm" method="post" class="tm-contact-form">
Name: <input type="text" id="contactName" name="contactName" class="form-control" placeholder="Name" required/>
<button type="button" id="inquire-button" class="btn btn-primary">Inquire</button>
<button type="submit" id="pay" class="btn btn-primary">Pay</button>
<div id="mail-status"> </div>
</form>

Controller method is not detecting any parameter

I'am trying to send an id in my url but my controller doesn't get that value
$("#ChangeSlideForm").on("submit", function(){
$.ajax({
type: "POST",
url: base_url + "Visualiser/ChangeSlide/21",
success: function (response) {
alert(response);
// $("#deleteConfirm").modal('hide');
// jQuery(function RefreshPageAdd($){
// $('#deleteConfirm').on('hidden.bs.modal', function (e) {
// location.reload();
// });
// });
}
});
});
My View
<div id="bodyChange" class="modal-body">
<form id = "ChangeSlideForm" action="<?php echo base_url() ?>Visualiser/ChangeSlide" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<label class="btnSlide btn btn-outline-success">
Zip <input class="file" name="file[]" type="file" hidden>
</label>
<label class="btnSlide btn btn-outline-success">
Csv <input class="file" name ="file[]" type="file" hidden>
</label>
</div>
<div class="modal-footer">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary col-md-6">Ajouter</button>
</div>
</form>
My controller header :
public function ChangeSlide($id){
print_r($id);
}
When I a put the id in the url directly then the parameter is accessible otherwise when I pass with ajax, It doesn't detect the parameter.
Try this:-
The HTML
<form id="ChangeSlideForm" action="<?php echo base_url() ?>Visualiser/ChangeSlide/21" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div id="bodyChange" class="modal-body">
<label class="btnSlide btn btn-outline-success"> Zip
<input class="file" name="file[]" type="file" hidden>
</label>
<label class="btnSlide btn btn-outline-success"> Csv
<input class="file" name="file[]" type="file" hidden>
</label>
</div>
<div class="modal-footer">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary col-md-6">Ajouter</button>
</div>
</div>
</form>
The Script:
<script type="text/javascript">
$(document).ready(function(){
$("#ChangeSlideForm").on("submit", function(e){
e.preventDefault();
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serializeArray(),
success : function(data)
{
console.log(data)
},
error: function (xhr)
{
console.log(xhr)
}
});
});
})
</script>
Try this
public function ChangeSlide(){
print_r($this->uri->segment(3));
}
You missing parameter data in $.ajax(). So your ajax didn't send any data to your controller
When you pass value with ajax then controller method get that value as $this->input->post('id'); not as parameter.
So you have to add following to method
public function ChangeSlide($id = "")
{
}

Dynamically Pass Form ID Into Function

I have several forms on a page and i want to utilize the same ajax function. It works great for one form since I am grabbing the id with getElementById and then passing it to my ajax function. What I am trying to do is pass down the id of the form onSubmit dynamically.
form
<form id="postData" name="business" method="post" action="{{ path('location_graph', {'location_id': location.getId }) }}"
class="m-form m-form--fit m-form--label-align-right">
<div class="form-group m-form__group row">
<label class="col-2 col-form-label required" for="description">Business
Description</label>
<div class="col-7">
<input type="text" class="form-control m-input" id="description"
name="extra[description]">
</div>
</div>
...
<div class="form-group m-form__group row">
<button type="submit" class="btn m-btn--square btn-outline-primary">
Submit
</button>
</div>
</form>
script
document.getElementById('postData').addEventListener('submit', postData);
function postData(event) {
event.preventDefault();
$.ajax({
type: $(this).attr("method"),
url: $(this).attr("action"),
data: $(this).serialize(),
success: function (data) {
console.log(data);
$('#success__para').html("You data was saved");
}
});
}
You can attach a submit event handler to each of the forms and pass event and this.id (the id of the form element) as arguments.
Javascript:
function postData(event, id) {
event.preventDefault();
var elem = $('#'+id);
$.ajax({
type: elem.attr("method"),
url: elem.attr("action"),
data: elem.serialize(),
success: function (data) {
console.log(data);
$('#success__para').html("You data was saved");
}
});
}
HTML:
<form id="someid" onsubmit="postData(event, this.id)">

Button is not working after first successful ajax data laod

var Update = {
init: function(){
$('.find').on('click', function(e){
e.preventDefault();
var
$this = $(this),
$form = $('#searchForm');
BLC.ajax({
url: "/emp/find",
type: 'POST',
data: data
},function(data){
$('#findEmployees').html(data);
});
});
}
};
<div id="findEmployees">
<blc:form method="POST" th:action="#{/emp/find" id="searchForm">
<input type="text" th:field="*{employee.id}" name="id" id="id" />
<button id="find" name="find" class="find" type="button"
th:text="Find"></button>
</blc:form>
<blc:form class="detailform" name="detailform"
th:action="#{/emp/deatils}" method="post">
<input type="hidden" th:id="id" th:name="id" th:value="*{id}" />
<a href="#" class="empLink">
<h4 th:text="*{id}"></h4>
</a>
</blc:form>
</div>
Because you are replacing the content in the div with the new content from the Ajax call, you need to reference the document and delegate the event handler to the newly added code.
$(document).on('click', '.find', function(e){....

Categories