Dynamically Pass Form ID Into Function - javascript

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)">

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) { /*...*/ });
}

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 = "")
{
}

HTML Form Submit does not reach my javascript

I am trying to reach my javascript code when I press the submit button within my form and it is not triggering my javascript code at all.
So I got this form within my Bootstrap Modal using the following code:
<form id="updateUserForm">
<div class="form-group">
<label for="firstName">First name:</label>
<input type="text" class="form-control" id="firstnameModalInput" />
</div>
<div class="form-group">
<label for="middleName">Middle name:</label>
<input type="text" class="form-control" id="middlenameModalInput" />
</div>
<div class="form-group">
<label for="lastName">Last name:</label>
<input type="text" class="form-control" id="lastnameModalInput" />
</div>
<div class="form-group">
<label for="mobileNumber">Mobile number:</label>
<input type="text" class="form-control" id="mobilenumberModalInput" />
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" id="emailModalInput" />
</div>
<div class="form-group">
<label for="Enabled">Enabled:</label>
<input type="checkbox" class="form-control" id="enabledModalInput" style="width:34px" />
</div>
<div class="modal-footer">
<input type="submit" class="btn btn-default" data-dismiss="modal" id="submit" value="Apply" />
</div>
</form>
And the javascript code I have:
$('document').ready(function(){
$("#updateUserForm").submit(function (event) {
console.log("Method entered");
event.preventDefault();
var serialize = $("#updateUserForm").serialize();
$.ajax({
type: "POST",
data: serialize,
url: "/Dashboard/UpdateUser",
datatype: JSON,
succes: function (data) {
console.log("succes!");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
})
})
})
I have another function in that javascript that is used to populate the input fields and that works fine, so I guess the HTML can reach the javascript file. But it does not reach the javascript submit function (it doesn't do the console.log for example) . Does anyone have an idea what I am doing wrong?
EDIT:
I have been playing around a bit more, and it seems that I can acces the javascript method when I try to reach it from outside of the bootstrap modal, it goes wrong somewhere within the modal.
Use return false instead of prevent default end of the function and change the submit function with on function.
$('document').ready(function(){
$("#updateUserForm").on("submit", function () {
console.log("Method entered");
var serialize = $("#updateUserForm").serialize();
$.ajax({
type: "POST",
data: serialize,
url: "/Dashboard/UpdateUser",
datatype: JSON,
succes: function (data) {
console.log("succes!");
console.log(data);
},
error: function (data) {
console.log("error");
console.log(data);
}
})
return false;
})
})
try this
$("#updateUserForm").on('submit', function (e) {
e.preventDefault();
});
Can you please try below code. and please check post URL"/Dashboard/UpdateUser" is right?
$("#UpdateUserForm").submit(function (e)
{
var isValid = $("#UpdateUserForm").valid();
if (!isValid)
return;
//This is important as it prevents the form being submitted twice
e.preventDefault();
$.ajax({
type: "POST",
url: "/Dashboard/UpdateUser",
data: $("#UpdateUserForm").serialize(),
success: function (response)
{
var status = '';
status = response.Status;
console.log("succes!");
console.log(data);
}
})
.error(function () {
console.log("error");
console.log(data);
});
});
$("#updateUserForm").on('submit', function (e) {
e.preventDefault();
});
Or use action properties in form.

Avoid Refreshing page submiting the form

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.

Form serialize issue

Here is my form's markup
<form name="contactForm" id="contactForm" role="form">
<div style="width: 190px">
<div class="form-group">
<input type="text" placeholder="fullname" name="fullname" id="formFullname" class="form-control">
</div>
<div class="form-group">
<input type="email" placeholder="email" name="email" id="fromEmail" class="form-control">
</div>
<div class="form-group">
<input type="text" placeholder="company" name="company" id="fromCompany" class="form-control">
</div>
</div>
<div class="clear"></div>
<div class="form-group">
<textarea placeholder="message" name="message" id="formMessage" rows="3" class="form-control"></textarea>
</div>
<button class="btn btn-success" type="submit" name="submit" id="formSubmit">send</button>
</form>
Using jquery 1.10.2
And here is JS
var form = $('#contactForm');
form.submit(function () {
console.log("form ", $(this).serialize());
$.ajax({
type: "POST",
url: url + "ajax/sendmail",
data: $(this).serialize(),
success: function (response) {
console.log(response);
}
});
return false;
});
I know that function fires, tested with alert. But console.log doesnt return anything, and during ajax call I don't see anything in POST (Watching with firebug's XHR).
BTW: role="form" is because i'm using Twitter Bootstrap framework
What am I doing wrong?
UPDATE
data: $(form).serialize() didn't help also
If you try this :
form.submit(function () {
console.log("form ", $(this).serialize());
return false;
});
it works just fine. So I think the problem
form.on('submit',function () {
event.preventDefault();
console.log("form ", $(this).serialize());
$.ajax({
type: "POST",
url: url + "ajax/sendmail",
data: $("form").serialize(),
success: function (response) {
console.log(response);
}
});
return false;
});
Because $(this) in your code doesn't refer to the form but instead refers to jQuery on which the ajax method is called
Try the following code, but first modify your form HTML so that is has an "action" attribute. The nice thing about this code is that it can be used on any form which has a submit button and an action attribute. (i.e. it is not coupled to any specific IDs)
$(function() {
$('input[type="submit"]').click(function(event) {
event.preventDefault();
var form = $(this).closest('form');
var url = form.attr('action');
var data = form.serialize();
$.post(url, data)
.done(function() {
alert('Yay! your form was submitted');
})
.fail(function() {
alert('Uh oh, something went wrong. Please try again');
});
});
Cheers.

Categories