Looping through an ajax script to process forms on a page - javascript

I have a page with lots of small one line forms, each of which has 5 items. The forms have the id form1, form2, form3, etc, and the id of the items and the submit button follows the same pattern. I have written out the following ajax script for processing the forms one at a time, where the variable $n corresponds to the form and item number. What I am not sure about is how to loop through this script for each form on the page. Do I need to somehow count the number of forms on the page first and then create a loop, and if so how do I do this?
$(".submit$n").click(function() {
var action = $("#form$n").attr('action');
var form_data = {
name: $j("#name$n").val(),
date: $j("#date$n").val(),
attended: $j("#attended$n").val(),
paid: $j("#paid$n").val(),
method: $j("#method$n").val(),
is_ajax: 1
};
$j.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response){
if(response == 'success')
$j("#form$n").fadeOut(800);
console.log(response);
}
});
return false;
});
});

I'm sorry but I don't think this is being set up correctly, and neither is the accepted answer...it's just very messy. I'm not sure if your original code is replicated for every form you have (because the whole $n variable thing confuses me and makes me think you have it several times), but it isn't needed if so. Here's what I would use:
$(document).ready(function () {
$(".submit").click(function () {
var $this = $(this);
var $form = $this.closest("form");
var action = $form.attr('action');
var form_data = {
name: $form.find("[id^=name]").val(),
date: $form.find("[id^=date]").val(),
attended: $form.find("[id^=attended]").val(),
paid: $form.find("[id^=paid]").val(),
method: $form.find("[id^=method]").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function (response) {
if (response == 'success') {
$form.fadeOut(800);
}
console.log(response);
}
});
return false;
});
});
Just give all the submit buttons a class of "submit", and this should work fine. Just to make sure, your HTML would have the format of this:
<form id="form1" action="page1.php">
<input type="text" id="name1" name="name1" /><br />
<input type="text" id="date1" name="date1" /><br />
<input type="text" id="attended1" name="attended1" /><br />
<input type="text" id="paid1" name="paid1" /><br />
<input type="text" id="method1" name="method1" /><br />
<input type="submit" class="submit" value="Submit" />
</form>
Just so you understand what's happening, the Javascript finds the submit button's parent form when it's clicked. Then, with that form, it finds all descendents that have an id attribute that starts with "name", "date", etc. You can do this because you have clearly separated controls into their own forms. So with this code, you can be assured that when you click a submit button, you're grabbing all of the controls' values from the form that it's in.

Add a common class to all your submit buttons, like: <input type="submit" id="submit1" name="submit1" class="submit" />
And then change your code to:
$('.submit').on('click', function() {
var n = this.id.substr(6);
// n is the number of the form. 6 because the word submit has 6 characters.
// You might want to do this some other way.
// you can get the rest of the values by doing
$('#name' + n).val()
// and so on
});

Related

Issue with AJAX form submit

Required the form to be submitted via an ajax call and you will intercept the result and update your page. You never leave the index page.
I'm having trouble having the ajax call working
<form action="/cart" method="post" id="addProduct">
Quantity: <input type="number" name="quantity">
<button type="submit">Add to Cart</button>
<input type="hidden" name="productid" value="{{id}}">
<input type="hidden" name="update" value="0">
</form>
var form = $('#addProduct');
form.submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/cart",
data: form,
dataType: "json",
success: function(e) {
window.location.href = "/";
}
});
})
you can use
JavaScript
new FormData(document.querySelector('form'))
form-serialize (https://code.google.com/archive/p/form-serialize/)
serialize(document.forms[0]);
jQuery
$("form").serializeArray()
You are changing the whole meaning of the ajax call. Ajax call is used for updating something without page refresh. In your case on success, you are changing the URL which is not right. Remove window.location.href = "/"; from your code and try to append messages or alert something like alert('Product is added to cart');
Your ajax call is not sending data to the server. Use formdata object or serialize() to get form input values then send it to the server.
Use
var form = new FormData($('#addProduct')[0]);
OR
var form = $("'#addProduct").serialize();
Instead of
var form = $('#addProduct');
And on success, send response from server and update your DOM in success function. Don't use window.location.href = "/";
To update your document after success you can use append(e) to update your DOM
<form method="post" id="addProduct">
Quantity: <input type="number" name="quantity">
<button type="submit">Add to Cart</button>
<input type="hidden" name="productid" value="2">
<input type="hidden" name="update" value="0">
</form>
<div id="display">
</div>
$(function(){
$("#addProduct").submit(function(e){
e.preventDefault();
var quantity = $(this).children("input[name=quantity]").val();
var productid = $(this).children("input[name=productid]").val();
var update = $(this).children("input[name=update]").val();
$.ajax({
type:"post",
url:"/cart.php",
data:{update:update,quantity:quantity,productid:productid},
success: function(feedback){
$("#display").html(feedback);
},
error: function(err){
alert("error");
}
});
});
});
I update my answer and i use the div with id display to show my data return from ajax success

php - ajax sending automatically all the inputs as an array [duplicate]

This question already has answers here:
jQuery AJAX submit form
(20 answers)
Closed 4 years ago.
I have a form that will often be changing.
I try to find a solution for not editing the AJAX call each time there is a change in the form.
So for exemple:
FORM:
<form>
<label>RED</label>
<input type="text" id="RED"><br>
<label>BLUE</label>
<input type="text" id="BLUE"><br>
<label>YELLOW</label>
<input type="text" id="YELLOW"><br>
<label>ORANGE</label>
<input type="text" id="ORANGE"><br>
<label>PINK</label>
<input type="text" id="PINK"><br>
<label>GREEN</label>
<input type="text" id="GREEN"><br>
<input type="submit" name="submit">
</form>
AJAX CALL:
<script type="text/javascript">
$(document).on("click", ".fiche_client--btn--actualiser", function(e){
e.preventDefault();
// Informations Personnelles
var RED = $('#RED').val();
var BLUE = $('#BLUE').val();
var YELLOW = $('#YELLOW').val();
var ORANGE = $('#ORANGE').val();
var PINK = $('#PINK').val();
var GREEN = $('#GREEN').val();
$.ajax({
type:'POST',
data:{
RED:RED,
BLUE:BLUE,
YELLOW:YELLOW,
ORANGE:ORANGE,
PINK:PINK,
GREEN:GREEN,
},
url:'/url/colors.php',
success:function(data) {
if(data){
alert('Pocket!');
}else{
alert('Update failed');
}
}
});
});
</script>
I'm trying to automatise the process for:
1/ The AJAX's call understand how many <input> there are, put them automatically in var in the javascript and also automatically in data in the ajax part.
2/ The script called by the ajax (/url/color.php) obtains the result as an array like this [RED] => input's content [BLUE] => input's content [YELLOW] => input's content (and so on...)
Is it something doable or totally impossible in php?
If I understand the question correctly, there is absolutely something for this in jQuery: it's called .serialize(). It will get all of the inputs in the form and create a query string out of them:
$(document).on("click", ".fiche_client--btn--actualiser", function(e){
e.preventDefault();
// Informations Personnelles
let data = $("form").serialize();
$.ajax({
type:'POST',
data: data,
url:'/url/colors.php',
success:function(data) {
if(data){
alert('Pocket!');
}else{
alert('Update failed');
}
}
});
});

Prevent redirecting after post

It's probably a bad idea to ask a question, which already have multiple answers and multiple times, but I should ask it anyway. I tried pretty much everything I find there Prevent redirect after form is submitted but nothing helps me.
There is a some minor detail, which I don't see. I'm not very familiar with jQuery and AJAX. Especially with the former.
So, the code:
<form id="form" action="uploadfile.php" method="post" enctype="multipart/form-data" ><!--action="uploadfile.php" onsubmit="return false;" -->
<label>Name</label>
<input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" /><br>
<label id="nameerror"></label><br>
<label>Email</label>
<input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')"/><br>
<label id="emailerror"></label><br>
Select a file<br />
<label id="draganddroperror"></label><br>
<input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple /><br />
<button id="btnSubmit" onclick="sendData()" style="background-color: gray; color: #ffffff;" />Отправить</button>
</form>
There is my JS
function sendData() {
var file_data = $("#fileToUpload").prop("files");
console.log(file_data);
if ($("#file_data").val() != "") {
var form_data = new FormData();
//form_data.append('file', file_data);
//console.log(file);
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadfile.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
// get server responce here
//alert(data);
// clear file field
//$("#your-files").val("");
return false;
}
});
return false; //event.preventDefault();
} else {
alert("Please select file!");
}
}
So, this is the code in question. All works flawlessly, except redirect. Another questions contains submit, but I didn't have submit input. I tried to delink form from post method (1st line), but I got server error. Return false everywhere.
I spent countless hours on this question, it consumed almost all my night hours for a few days. I would appreciate any help, thanks.
The trick to prevent form submission is return false onsubmit as below:
<form id="form" onsubmit="return sendData()" method="post" enctype="multipart/form-data">
<!--action="uploadfile.php" onsubmit="return false;" -->
<label>Name</label>
<input id="username" name="username" type="text" onblur="checkUsername(this.value)" onkeypress="clearError('nameerror')" oninput="clearError('nameerror')" />
<br>
<label id="nameerror"></label>
<br>
<label>Email</label>
<input id="email" name="email" type="text" onblur="validateEmail(this.value)" onkeypress="clearError('emailerror')" />
<br>
<label id="emailerror"></label>
<br> Select a file
<br />
<label id="draganddroperror"></label>
<br>
<input name="fileToUpload[]" id="fileToUpload" type="file" onchange="onChange(event)" multiple />
<br />
<button type="submit" id="btnSubmit" style="background-color: gray; color: #ffffff;">Upload</button>
</form>
Note that I have written onsubmit=return sendData(). When the sendData() will return true the form will get submitted, otherwise it will never get submitted. For that the last statement in sendData() is return false;. In this way the form never gets submitted in current window, instead only Ajax submit works.
function sendData() {
var file_data = $("#fileToUpload").prop("files");
console.log(file_data);
if ($("#file_data").val()) {
var form_data = new FormData();
//form_data.append('file', file_data);
//console.log(file);
form_data.append('file', file_data);
console.log(form_data);
$.ajax({
url: 'uploadfile.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data) {
// get server responce here
//alert(data);
// clear file field
//$("#your-files").val("");
}
});
} else {
alert("Please select file!");
}
return false;
}
I hope this gives you the clear understanding.
You want to cancel the default event handler for the submit event that the button triggers. To do this you need access to the event itself. It's best practice to handle the button click from JavaScript entirely instead of calling functions from HTML.
var submitButton = document.getElementById('btnSubmit');
submitButton.addEventListener('click', sendData);
// Then you will have access to the event in the sendData function
function sendData(ev) {
ev.preventDefault();
...
}
Live example
A slightly cleaner approach is to handle the form submitting, however this is done. This would also catch a form submit by hitting the enter key for example.
var form = document.getElementById('form');
form.addEventListener('submit', sendData);
Live example
In function sendData() you should pass event param like this
function sendData(evt) {
}
and then in this function we should add evt.preventDefault(); to stop submit action. Hope this help.
Add type attribute with the value of button and you are done:
<button id="btnSubmit" type="button" ...
By default The value for the type attribute is submit, which tells the browser to submit the from to the server, If you change it to button the browser will do nothing, you can only bind events when the button is clicked

strange behaviour - serialize

i have this code:
var sizes = ["1/9","1/8","1/7","1/6","1/5","1/4","1/3","1/2","1/1","2/1","3/1","4/1","5/1","6/1","7/1","8/1","9/1"];
var slider = new dijit.form.HorizontalSlider({
value:8,
name:"value"+[i],
slideDuration:0,
onChange:function(val){
dojo.byId('value'+[i]).value = sizes[val];
},
minimum:0,
maximum:sizes.length-1,
discreteValues:sizes.length,
intermediateChanges:"true",
},node);
now, when i made:
$("#custom").submit(function() {
var formdata = $("#custom").serializeArray();
$.ajax({
url: "insert.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data) {
}
});
For example, if i choose the value 1/8 it is sent as 1, or 9/1 as 16.
What i want is send the fraction value, that is showed in the input box, but as i said, not sent to the insert.php
Any idea ? thanks
At the beginning during the init of the slider an <input type="hidden" name="input0" ... /> will be created.
After using the slider this input get the current slider value (a number between 0 and sizes.length - 1). The onChange sets an other html input tag with the value from the array called sizes.
While submitting the serializeArray() takes the values of all input fields which have a name attribute.
In my EXAMPLE I gave the input field that will be filled at the onChange a name attribute, so the serialization takes both values.
HTML:
<form action="#" id="custom">
<div id="slider0"></div>
<input type="text" id="value0" data-dojo-type="dijit.form.TextBox" name="value0" />
<input type="submit" value="submit" />
</form>

How to pass multiple checkboxes using jQuery ajax post

How to pass multiple checkboxes using jQuery ajax post
this is the ajax function
function submit_form(){
$.post("ajax.php", {
selectedcheckboxes:user_ids,
confirm:"true"
},
function(data){
$("#lightbox").html(data);
});
}
and this is my form
<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
From the jquery docs for POST (3rd example):
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Just came across this trying to find a solution for the same problem. Implementing Paul's solution I've made a few tweaks to make this function properly.
var data = { 'venue[]' : []};
$("input:checked").each(function() {
data['venue[]'].push($(this).val());
});
In short the addition of input:checked as opposed to :checked limits the fields input into the array to just the checkboxes on the form. Paul is indeed correct with this needing to be enclosed as $(this)
Could use the following and then explode the post result explode(",", $_POST['data']); to give an array of results.
var data = new Array();
$("input[name='checkBoxesName']:checked").each(function(i) {
data.push($(this).val());
});
Here's a more flexible way.
let's say this is your form.
<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
And this is your jquery ajax below...
// Don't get confused at this portion right here
// cuz "var data" will get all the values that the form
// has submitted in the $_POST. It doesn't matter if you
// try to pass a text or password or select form element.
// Remember that the "form" is not a name attribute
// of the form, but the "form element" itself that submitted
// the current post method
var data = $("form").serialize();
$.ajax({
url: "link/of/your/ajax.php", // link of your "whatever" php
type: "POST",
async: true,
cache: false,
data: data, // all data will be passed here
success: function(data){
alert(data) // The data that is echoed from the ajax.php
}
});
And in your ajax.php, you try echoing or print_r your post to see what's happening inside it. This should look like this. Only checkboxes that you checked will be returned. If you didn't checked any, it will return an error.
<?php
print_r($_POST); // this will be echoed back to you upon success.
echo "This one too, will be echoed back to you";
Hope that is clear enough.
This would be better and easy
var arr = $('input[name="user_ids[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The following from Paul Tarjan worked for me,
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
but I had multiple forms on my page and it pulled checked boxes from all forms, so I made the following modification so it only pulled from one form,
var data = { 'user_ids[]' : []};
$('#name_of_your_form input[name="user_ids[]"]:checked').each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Just change name_of_your_form to the name of your form.
I'll also mention that if a user doesn't check any boxes then no array isset in PHP. I needed to know if a user unchecked all the boxes, so I added the following to the form,
<input style="display:none;" type="checkbox" name="user_ids[]" value="none" checked="checked"></input>
This way if no boxes are checked, it will still set the array with a value of "none".
function hbsval(arg) {
// $.each($("input[name='Hobbies']:checked"), function (cobj) {
var hbs = new Array();
$('input[name="Hobbies"]:checked').each(function () {
debugger
hbs.push($(this).val())
});
alert("No. of selected hbs: " + hbs.length + "\n" + "And, they are: " + hbs[0] + hbs[1]);
}

Categories

Resources