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) { /*...*/ });
}
Related
I have a simple form with Ajax call, but ajax call gets executed even if form is not validated.
In below code line console.log("This line should execute only if Form is validated"); gets executed when form is not validate.
Bootstrap 5 validation Codepen code
(function () {
"use strict";
const forms = document.querySelectorAll(".requires-validation");
Array.from(forms).forEach(function (form) {
form.addEventListener(
"submit",
function (event) {
if (!form.checkValidity()) {
event.preventDefault();
event.stopPropagation();
}
else
{
console.log("This line should execute only if Form is validated");
// Call Ajax Function
// AjaxCallSaveData();
}
form.classList.add("was-validated");
},
false
);
});
})();
//$(document).ready(function () {
function AjaxCallSaveData()
{
$("form").submit(function (event) {
var formData = {
name: $("#name").val(),
email: $("#email").val(),
message: $("#message").val(),
superheroAlias: $("#superheroAlias").val()
};
$.ajax({
type: "POST",
url: "SubmitFORM.php",
data: formData,
dataType: "json",
encode: true
}).done(function (data) {
console.log(data);
});
event.preventDefault();
});
}
//});
Not sure if i am doing it right?
HTML
<div class="form-body">
<div class="row">
<div class="form-holder">
<div class="form-content">
<div class="form-items">
<h3>Register you interest</h3>
<p>Fill in the data below, we will get back to you!</p>
<form class="requires-validation" action="SubmitFORM.php" method="POST" novalidate>
<div class="col-md-12 mb-3">
<input class="form-control" type="text" name="name" id="name" placeholder="Full Name" required>
<div class="valid-feedback">Username field is valid!</div>
<div class="invalid-feedback">Username field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<input class="form-control" type="email" name="email" id="email" placeholder="E-mail Address" required>
<div class="valid-feedback">Email field is valid!</div>
<div class="invalid-feedback">Email field cannot be blank!</div>
</div>
<div class="col-md-12 mb-3">
<textarea name="message" id="message" placeholder="Your Message"></textarea>
</div>
<div class="form-button mt-3">
<button id="submit" type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
event.preventDefault() will only stop the form from submitting. It cannot stop next lines of the JavaScript function from executing.
You should use return in place of event.preventDefault().
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>
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)">
Whenever using this form that I made (in Portuguese), refreshing removes all previously entered data from the page. Why does this happen, and how can I fix it? Thank you for your time.
<script type="text/javascript">
function submitForm(){
// Initiate Variables With Form Content
var nome = $("#nome").val();
var email = $("#email").val();
var telefone = $("#telefone").val();
var assunto = $("#assunto").val();
var mensagem = $("#mensagem").val();
$.ajax({
type: "POST",
url: "send-contact2.php",
data: "nome=" + nome + "&email=" + email + "&telefone=" + telefone + "&assunto=" + assunto + "&mensagem=" + mensagem,
cache:false,
success: function (data) {
alert(data);
}
});
}
</script>
<form id="myForm">
<div class="col col-md-6">
<input type="text" name="nome" id="nome" required value="" tabindex="1" placeholder="Nome">
<input type="text" name="email" id="email" required value="" tabindex="2" placeholder="E-mail">
<input type="text" name="telefone" id="telefone" required value="" tabindex="2" placeholder="Telefone">
<select id="assunto" name="assunto" required>
<option value="outros">Outros assuntos</option>
<option value="encomendas">Encomendas</option>
</select>
</div>
<div class="col col-md-6">
<textarea name="mensagem" id="mensagem" cols="29" rows="8" placeholder="Mensagem"></textarea>
</div>
<div class="col col-md-12 ">
<button name ="submit" type="submit" onclick="return submitForm();">Enviar</button>
</div>
</form>
Your function also needs to return false to stop the click event behaviour from submitting the form:
function submitForm(){
// your code...
return false;
}
Better still, hook to the submit event of the form directly and do away with the clunky onclick handlers, and use serialize() to gather the form data for you:
<button name="submit" type="submit">Enviar</button>
<script type="text/javascript">
$(function() {
$('#myForm').submit(function(e) {
e.preventDefault(); // stop form submission
$.ajax({
type: "POST",
url: "send-contact2.php",
data: $(this).serialize(),
cache: false,
success: function (data) {
alert(data);
}
});
}
});
</script>
Try to change onClick action to onSubmit and add return false after method. Like this:
<button name ="submit" type="submit" onsubmit="submitForm(); return false;">Enviar</button>
Good practice will be add method="POST" to your form attributes.
I have created a form with two listboxes in which it is possible to move the items from one listbox into another.
The view also loads correctly, but I haven't figured out how to send the modified listbox data back to controller.
The view code is the following:
<script>
$(function() {
$(document)
.on("click", "#MoveRight", function() {
$("#SelectLeft :selected").remove().appendTo("#SelectRight");
})
.on("click","#MoveLeft", function() {
$("#SelectRight :selected").remove().appendTo("#SelectLeft");
});
});
#Html.Hidden("RedirectTo", Url.Action("UserManagement", "Admin"));
<h2>User</h2>
<div class="container">
<form role="form">
<div class="container">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<label for="SelectLeft">User Access:</label>
<select class="form-control" id="SelectLeft" multiple="multiple" data-bind="options : ownership, selectedOptions:ownership, optionsText:'FirstName'">
</select>
</div>
</div>
<div class="col-md-2">
<div class="btn-group-vertical">
<input class="btn btn-primary" id="MoveLeft" type="button" value=" << " />
<input class="btn btn-primary" id="MoveRight" type="button" value=" >> " />
</div>
</div>
<div class="col-md-5">
<div class="form-group">
<label for="SelectRight">Owners:</label>
<select class="form-control" multiple="multiple" id="SelectRight" multiple="multiple" data-bind="options : availableOwners, selectedOptions:availableOwners, optionsText:'FirstName'">
</select>
</div>
</div>
</div>
</div>
</form>
</div>
<script>
var data=#(Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model)));
var selectedOwners = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.AccessOwners));
var availableOwners = #Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(ViewBag.Owners));
function viewModel() {
this.username=ko.observable(data.Username);
this.password=ko.observable(data.Password);
this.email=ko.observable(data.Email);
this.isActive=ko.observable(data.IsActive);
this.userId = ko.observable(data.UserId);
this.ownership=ko.observableArray(selectedOwners);
this.availableOwners = ko.observableArray(availableOwners);
this.submit = function()
{
$.ajax({
url: '#Url.Action("UserSave", "Admin")',
type: 'POST',
data: ko.toJSON(this),
contentType: 'application/json',
});
window.location.href = url;
return false;
}
this.cancel = function()
{
window.location.href = url;
return false;
}
};
ko.applyBindings(new viewModel());
var url = $("#RedirectTo").val();
I would be very thankful if anyone could suggest the way to pass all the selected options back to controller by populating the data with modified lists when the submit function is executed.
Thanks!
Before form submission save one side items values in an hidden input element. (comma separated values of listbox items.) The value of hidden element is sent to server by submitting the form. In controller you can do the next things.