How to Submit appended form separately - javascript

There is a button labeled NEWFORM to create a new form when clicked. Each form has a submit button. When the submit button of each form is clicked, the values of that form will be sent via AJAX. My code works well the first time, but when a new form is created and submitted, all of the values of all forms will send together.
Here is my snippet:
$(document).ready(function() {
$(".newform").click(function() {
$(".MyForm")
.eq(0)
.clone()
.show()
.insertAfter(".MyForm:last");
});
$(document).on('click', '.MyForm button[type=submit]', function(e) {
e.preventDefault() // To make sure the form is not submitted
$('.MyForm').each(function() {
console.log($(this).serialize())
$.ajax(
$(this).attr('action'),
{
method: $(this).attr('method'),
data: $(this).serialize()
}
)
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<span class="newform">NEWFORM+</span>
<div class="all">
<form class="MyForm" method="post">
<input type="text" placeholder="name" value="Aynaz" name="a1" />
<select name="Avg">
<option value="1">1</option>
<option value="2">2</option>
</select>
<button type="submit">Submit</button>
</form>
</div>

You iterate all ".MyForm" objects in your solution, so all of them submitted, you need to determine correct form in onClick first, and then submit it:
$(document).ready(function() {
$(".newform").click(function() {
$(".MyForm")
.eq(0)
.clone()
.show()
.insertAfter(".MyForm:last");
});
$(document).on('click', '.MyForm button[type=submit]', function(e) {
e.preventDefault() // To make sure the form is not submitted
var $frm = $(this).closest('.MyForm');
console.log($frm.serialize());
$.ajax(
$frm.attr('action'),
{
method: $frm.attr('method'),
data: $frm.serialize()
}
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<span class="newform">NEWFORM+</span>
<div class="all">
<form class="MyForm" method="post">
<input type="text" placeholder="name" value="Aynaz" name="a1" />
<select name="Avg">
<option value="1">1</option>
<option value="2">2</option>
</select>
<button type="submit">Submit</button>
</form>
</div>

$(document).ready(function() {
$(".newform").click(function() {
$(".MyForm")
.eq(0)
.clone()
.show()
.insertAfter(".MyForm:last");
});
$(document).on('click', '.MyForm button[type=submit]', function(e) {
e.preventDefault() // To make sure the form is not submitted
var $this = $(this).closest("form");
console.log($this.serialize())
$.ajax(
$(this).attr('action'),
{
method: $this.attr('method'),
data: $this.serialize()
}
)
});
});

You could do this rather
$(document ).on('submit', '.myForm', function(e) {
e.preventDefault()
$.ajax({
type: 'post',
data: $(this).serialize(),
url: 'submit.php'
})
})
The problem is your contextual application of $(this)

Related

PHP Submitting a form without refreshing the page and call a function

We have created a feedback form and once a user submits the feedback, we want to run the function that submits it to Airtable and then show the Next button.
Problem: The jQuery is working, showing the button after submit, but the function in (isset($_POST['submit']) isn't saving at all.
I've read through many posts but can't find the answer. Any help would be great!
Here is our current code
public function airtable_function() {
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#nameFrm").submit(function (e) {
e.preventDefault();
var frm = jQuery('#nameFrm');
var outPut = jQuery('#results');
var loadButton = jQuery('#loadingImage');
var comments = jQuery('#comments').val();
var reason = jQuery('#reason').val();
jQuery.ajax({
type: 'POST',
data:'action=submitForm&comments='+comments+'&reason='+reason,
url: 'requests.php',
beforeSend: function(){
loadButton.show();
},
complete: function(data){
loadButton.show();
frm.hide();
},
success: function(data) {
frm.hide();
outPut.html(data);
}
});
});
});
</script>
<div>
<form action="requests.php" id="nameFrm" name="frmName" method="POST" >
<p>Please give us feedback</p>
<select id="reason" name="reason" required>
<option value="Choose a reason">Choose a reason</option>
<option value="Reason1">Reason1</option>
<option value="Reason2">Reason2</option>
<option value="Reason3">Reason2</option>
<option value="Other">Other</option>
</select>
<input id="comments" type='text' name='comments' required />
<input type="submit" value="submit" name="subbtn" >
</form>
<div id="loadingImage" style="display:none; text-align:center;">
Yes, Cancel Account
</div>
</div>
<div id="results"></div>
</div>
<?php
if (isset($_POST['submit'])){
$reason = $_POST['reason'];
$comments = $_POST['comments'];
save($reason, $comments);
}
?>
<?php
}
I assume you want to transfer the entries "reason" and "comment" to the page "requests.php". Then you don't need the second post request because you use ajax:
<?php
function airtable_function() {
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#nameFrm").submit(function (e) {
e.preventDefault();
var frm = jQuery('#nameFrm');
var outPut = jQuery('#results');
var loadButton = jQuery('#loadingImage');
var comments = jQuery('#comments').val();
var reason = jQuery('#reason').val();
jQuery.ajax({
type: 'get',
data: { 'result' : comments +'*'+reason, 'feedback' : 'true' },
url: 'requests.php',
beforeSend: function(){
loadButton.show();
},
complete: function(data){
loadButton.show();
frm.hide();
},
success: function(data) {
frm.hide();
outPut.html(data);
}
});
});
});
</script>
<div>
<form action="requests.php" id="nameFrm" name="frmName" method="POST" >
<p>Please give us feedback</p>
<select id="reason" name="reason" required>
<option value="Choose a reason">Choose a reason</option>
<option value="Reason1">Reason1</option>
<option value="Reason2">Reason2</option>
<option value="Reason3">Reason3</option>
<option value="Other">Other</option>
</select>
<input id="comments" type='text' name='comments' required />
<input type="submit" value="submit" name="subbtn" >
</form>
<div id="loadingImage" style="display:none; text-align:center;">
Yes, Cancel Account
</div>
</div>
<div id="results"></div>
</div>
<?php
}
The "request.php" looks like this:
<?php
if(isset($_GET['feedback']))
{
$result = $_GET['result'];
$parts = explode("*", $result);
print "reason: ".$parts[1]."<br>";
print "comments: ".$parts[0]."<br>";
}
?>
What I can see from the snippet is that:
if (isset($_POST['submit'])){
While the submit button is:
<input type="submit" value="submit" name="subbtn" >
Just fix this line:
isset($_POST['submit'] to isset($_POST['subbtn']
Hope this helps.

Jqueryvalidate's .validate() method does not execute in ASP Core

I'm trying to submit the form via ajax and it works fine but there was no validation. So I've added the JQuery validation library and added the code into handler as stated in the documentation but it doesnt seem to execute
The cshtml page:
#{
ViewData["Title"] = "CreateProduct";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1 class="text-center">Create Product</h1>
<br>
<form method="post" id="formdata" asp-controller="Product" asp-action="UploadProduct">
<div class="form-group">
<p>Please provide a name for your product:</p>
<input type="text" name="Name" required />
</div>
<div class="form-group">
<p>Please provide a price for your product:</p>
<input type="number" name="Price" required />
</div>
<div class="form-group">
<p>Please provide a description for your product:</p>
<input type="text" name="Description" required />
</div>
</form>
<button class="btn btn-primary" id="subBtn">Upload Files</button>
#section scripts
{
<script>
$(function () {
$('#subBtn').click(function (e) {
var formData = $('#formdata').serialize();
$('#formdata').validate({
debug: true,
submitHandler: function () {
$.ajax({
type: 'POST',
url: '/Product/UploadProduct',
data: formData,
success: function (e) {
Toastify({
text: "Product submition successful!",
duration: 3000,
gravity: "bottom", // `top` or `bottom`
position: 'right', // `left`, `center` or `right`
backgroundColor: 'blue',//"linear-gradient(to right, #00b09b, #96c93d)",
stopOnFocus: true, // Prevents dismissing of toast on hover
onClick: function () { } // Callback after click
}).showToast();
$(':input', '#formdata')
.not(':button, :submit, :reset, :hidden')
.val('')
.prop('checked', false)
.prop('selected', false);
}
}).fail(function (e) {
//toastr.error('Product not added');
});
}
});
});
});
</script>
}
And I've added the reference to the _Layout.cshtml:
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation/dist/additional-methods.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
</environment>
Once again I'd like to add that the logic is working, it's just that the validate() method doesn't execute.
The .validate() method is only used to initialize the plugin on your form. It does not belong inside of the click handler of the submit button. You should move the validate() method outside of the client handler , and serialize data inside the submitHandler event :
<script>
$(function () {
$('#formdata').validate({
submitHandler: function () {
var formData = $('#formdata').serialize();
alert("ad");
$.ajax({
type: 'POST',
url: '/Product/UploadProduct',
data: formData,
success: function (e) {
Toastify({
text: "Product submition successful!",
duration: 3000,
gravity: "bottom", // `top` or `bottom`
position: 'right', // `left`, `center` or `right`
backgroundColor: 'blue',//"linear-gradient(to right, #00b09b, #96c93d)",
stopOnFocus: true, // Prevents dismissing of toast on hover
onClick: function () { } // Callback after click
}).showToast();
$(':input', '#formdata')
.not(':button, :submit, :reset, :hidden')
.val('')
.prop('checked', false)
.prop('selected', false);
}
}).fail(function (e) {
//toastr.error('Product not added');
});
}
});
});
</script>
You can then use submit button inside form tag to trigger submit :
<form method="post" id="formdata" asp-controller="Product" asp-action="UploadProduct">
<div class="form-group">
<p>Please provide a name for your product:</p>
<input type="text" name="Name" required />
</div>
<div class="form-group">
<p>Please provide a price for your product:</p>
<input type="number" name="Price" required />
</div>
<div class="form-group">
<p>Please provide a description for your product:</p>
<input type="text" name="Description" required />
</div>
<button type="submit" class="btn btn-primary" name="submit" id="ajaxsubBtn1">Upload Files</button>
</form>

Update query insert if I want to edit row in PHP

I created a page, where I can easily update or insert data. It actually works, but if I click on the edit button, then I close the modal, then I add new data, it updates the previous data instead of inserting a new row. But if I refresh a page, then I update a row, it works. How can I solve this problem?
index.php:
<form method="post" id="insert_form">
<label><b>Name:</b></label>
<input type="text" name="name" id="name" class="form-control" readonly required />
<br />
<label><b>Description:</b></label>
<input type="text" name="hu" id="hu" class="form-control"></textarea>
<br />
<label><b>Cégek:</b></label>
<select name="company[]" id="company" multiple>
<?php
while($row = $huResult2->fetch_array()) {
?>
<option value="<?php echo $row['company_id'];?>"><?php echo $row['company_name'];?></option>
<?php
}
?>
</select>
<br/><br/>
<input type="hidden" name="data_id" id="data_id" />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-success" />
</form>
<script>
$('#add').click(function() {
$('#insert').val("Insert");
$('#insert_form')[0].reset();
$('#company').multiselect('refresh');
$('#name').removeAttr('readonly');
});
// Edit roles
$(document).on('click', '.edit_data', function() {
$("#company option").prop("selected", false);
$("#name").attr('readonly', true);
var data_id = $(this).attr("id");
// Receive the current datas for the roles
$.ajax({
url: "fetchRole.php",
method: "POST",
data: {
'data_id': data_id
},
dataType: "json",
success: function(data) {
$('#name').val(data.name);
$('#hu').val(data.hu);
$.each(data.companies, function(i, e) {
$("#company option[value='" + e + "']").prop("selected", true);
});
$('#company').multiselect('refresh');
$('#data_id').val(data.id);
$('#insert').val("Update");
$('#add_data_Modal').modal('show');
}
});
});
$('#insert_form').on("submit", function(e) {
e.preventDefault();
// Update and insert
$.ajax({
url: "insertRole.php",
method: "POST",
data: $('#insert_form').serialize(),
beforeSend: function() {
$('#insert').val("Updating...");
},
success: function(data) {
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#role_table').html(data);
location.reload();
}
});
});
</script>
Do one thing make data_id field value blank when you are closing the modal
$('#myModal').on('hidden.bs.modal', function () {
$("#data_id").val("");
})
Maybe it will help
or on click of add new button do the same
$('#add').click(function() {
$('#insert').val("Insert");
$('#insert_form')[0].reset();
$('#company').multiselect('refresh');
$("#data_id").val("");
$('#name').removeAttr('readonly');
});

How to post form submit to database along with ID logged in console

I am trying to add a form submission in a bootstrap modal along with an ID of the row that was clicked to open to modal to a database. I can add the ID alone and I can add the form submission alone, but I cannot combine these two sources of information in the same database.
In the code below I get the ID (var uid), and it is logged in the console.
Is it possible to add that logged value to the ajax post? And how can I do that, so it is sent along with the form values?
$(document).ready(function () {
$(document).on('click', '#getUser', function(e){
e.preventDefault();
var uid = $(this).data('id'); // get id of clicked row
console.log(uid);
$("#bestilform").on("submit", function(e) {
var formURL = $(this).attr("action");
var antal_ordre = $("antal_ordre").val();
var navn_ordre = $("navn_ordre").val();
var email_ordre = $("email_ordre").val();
var telefonnummer_ordre = $("telefonnummer_ordre").val();
$.ajax({
url: formURL,
type: "POST",
data: {'id': uid, 'antal_ordre': antal_ordre, 'navn_ordre': navn_ordre, 'email_ordre': email_ordre, 'telefonnummer_ordre': telefonnummer_ordre},
dataType: 'json'
})
hide modalcontant and show order
success: function(data, textStatus, jqXHR) {
$("#seordre").show();
$("#afgivordre").hide();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
//submit form with id #submitForm
$("#submitForm").on('click', function() {
$("#bestilform").submit();
});
});
</script>
this data: 'id': uid just gives me a 0 in the database. I am converting to integer in my php file.
Define your var uid outside of the function which sets it and the function which needs it. Make it global for both functions. (not the best way to do). The better way to pass the parameter to the function which does submit. In this case you'll achieve consistency and your UID never will be undefined. You code may looks like ...
$(document).ready(function() {
//define variable
var uid;
$(document).on('click', '#getUser', function(e) {
e.preventDefault();
// set it in one function
uid = $(this).data('id'); // get id of clicked row
console.log(uid);
// and call another one
$("#bestilform").submit();
});
$("#bestilform").on("submit", function(e) {
var formURL = $(this).attr("action");
var antal_ordre = $("select[name$='antal_ordre']").val();
var navn_ordre = $("input[name$='navn_ordre']").val();
var email_ordre = $("input[name$='email_ordre']").val();
var telefonnummer_ordre = $("input[name$='telefonnummer_ordre']").val();
// uid will be avaiable over here
$.ajax({
url: formURL,
type: "POST",
data: {
'id': uid,
'antal_ordre': antal_ordre,
'navn_ordre': navn_ordre,
'email_ordre': email_ordre,
'telefonnummer_ordre': telefonnummer_ordre
},
dataType: 'json'
});
// something else???
return false;
});
//submit form with id #submitForm
$("#submitForm").on('click', function() {
$("#bestilform").submit();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="getUser" data-id="67">click me</td>
</tr>
</table>
<br><br>
<form method="post" action="bestil.php" data-toggle="validator" role="form" class="form-group" id="bestilform">
<!-- antal måltider, som køber vil bestille-->
<div class="form-group">
<label>Antal måltider</label>
<select class="form-control selectpicker" name="antal_ordre">
<option value="1" selected>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
<!-- navn på køber-->
<div class="form-group">
<label for="InputName1">Fulde Navn</label>
<input name="navn_ordre" type="text" class="form-control" id="exampleInputName1" placeholder="Indtast dit navn">
</div>
<!-- email på køber-->
<div class="form-group">
<label for="InputEmail1">Email</label>
<input name="email_ordre" type="email" class="form-control" id="exampleInputEmail1" placeholder="Indtast din e-mail" data-error="Hov! Det er vist ikke en email...">
<div class="help-block with-errors"></div>
</div>
<!-- telefonnummer på køber-->
<div class="form-group">
<label for="InputPhonenumber1">Telefonnummer</label>
<div class="input-group">
<span class="input-group-addon">+45 </span>
<input name="telefonnummer_ordre" data-minlength="8" type="number" class="form-control" id="exampleInputPhone1" placeholder="Indtast dit telefonnummer">
</div>
</div>
<!--modal footer-->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" data-toggle="modal" data-target="#lavbestillingaccepter">Tilbage
</button>
<button type="button" class="btn btn-primary" id="submitForm" form="bestilform">Køb Måltid!
</button>
</div>
</form>

search form doesn't submits

I have this search form:
JSFIDDLE
and it doesn't submits. When I click to enter or search icon. why?
<form action="/search.php" method="get">
<fieldset>
<ul class="toolbar clearfix">
<li><button type="submit" id="btn-search"><span class="fa fa-search" style="color:gray;"></span></button></li>
<li><input type="search" id="search" placeholder="" name="s"></li>
</ul>
</fieldset>
</form>
$(document).ready(function() {
$('#btn-search').on('click', function(e) {
e.preventDefault();
$('#search').fadeIn().focus();
});
});
Because you are preventing form submit with e.preventDefault()
and not submitting form with any other methods.
You can submit your form using ajax like this:
$('#btn-search').on('click', function(e) {
e.preventDefault();
if( $('#search').val() ){
$.ajax({
url : 'submit.php',
data : { 'input': $('#search').val() },
success : function( response ) {
alert( response );
}
});
}
$('#search').animate({
width: 'toggle',
}).focus();
});
and write submit functions in submit.php
Inside submit.php you can write what you need to do with user input. Something like this:
<?php
echo "You have entered: " . $_GET['input'];
?>
Hope this helps..

Categories

Resources