How to pass multiple checkboxes using jQuery ajax post - javascript

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]);
}

Related

how to pass values from multiple textfields with same name attributes to a variable in form of an array

I am building a form that passes a set of numbers in form of an array to a variable as seen below
var users=["1","2"];
the main purpose of this is to then make an Ajax request with these numbers and get their corresponding content in my database which I then pass to their respective divs, please see below
var users=["1","2"];
var async_request=[];
var responses=[];
for(i in users)
{
// you can push any aysnc method handler
async_request.push($.ajax({
url:'back.php', // your url
method:'post', // method GET or POST
data:{user_name: users[i]},
success: function(data){
console.log('success of ajax response')
responses.push(data);
}
}));
}
$.when.apply(null, async_request).done( function(){
// all done
console.log('all request completed')
console.log(responses);
$( '#responses' ).html(responses[1]);
$( '#responses1' ).html(responses[0]);
});
This works perfectly.
But now I want to make some adjustments to my solution specifically
Im looking to replace the method of passing the numbers to the variable users
from
var users=["1","2"]; // Im looking to replace the method
to this
var users = $('[name="tom[]"]').val(attachArray);
<input type="text" name="tom[]" value="1" /><br>
<input type="text" name="tom[]" value="2" /><br>
but I am unable to get the the ids from the two textfields and then pass to my database using my Ajax script as I did before with this
var users=["1","2"];
You mean
const arr = ["1", "2"]
$('[name^=tom]').val(function(i) {
return arr[i]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="tom[]" value="" /><br>
<input type="text" name="tom[]" value="" /><br>
or
$('[name^=tom]').each(function() {
async_request.push($.ajax({
url:'back.php',
method:'post',
data:{user_name: this.value },
You forgot to use input key value :
var users = $('input[name="tom[]"]').val();

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');
}
}
});
});

JQuery in MVC - Send form data as array with getJson

I have an MVC view which updates the elements on the page by using getJSON pointing at a method in my controller periodically and parsing the returned Json.
Method blueprint in controller:
public JsonResult GetAttendeeJson()
{
//Code which creates the Json I need.
return Json(result, JsonRequestBehavior.AllowGet);
}
Call from View:
function showDetects() {
// This is the main AJAX that retrieves the data.
$.getJSON('/Attendee/CardDetections', function (data) {
$.each(data, function (i, country) {
// perform actions using data.
});
});
}
It's not important to understand what I'm doing but my circumstances have changed and I have now added to my view a form containing a variable amount of checkboxes (depending on which user uses the page the number of checkboxes will be different).
Checkbox form creation:
<form onsubmit="#Url.Action("Index", "Attendee")" method="post" id="checkboxform">
#{int i = 0;}
#{foreach (string s in ViewBag.LocationNames)
{
<div class="radio-inline">
#s
<input class="checkboxcontrol" onchange="this.form.submit()" type="checkbox" id="CheckBoxes" name="CheckBoxes" value="#ViewBag.LocationIds[i]">
</div>
i++;
}
}
</form>
The addition of this form means I now require my controller method which returns the Json to be able to use the data of these checkboxes. The GetAttendeeJson now needs to know which checkboxes are currently checked on the form.
So I want the method blueprint to be like:
public JsonResult GetAttendeeJson(int[] checkBoxValues)
{
//Code which creates the Json I need using the checkbox values.
return Json(result, JsonRequestBehavior.AllowGet);
}
Is it possible to do this without submitting the form? I use the submit to do something else which leads to reloading the page. I use the getJson to just update page content.
Ideally I'd just like to get the Value field of the checked checkboxes in an array and send it to the GetAttendeeJson function as a parameter when calling it.
Thanks,
JK
Lets say you have following HTML -
<input type="checkbox" name="chk" value="1" /> 1
<input type="checkbox" name="chk" value="2" /> 2
<input type="checkbox" name="chk" value="3" /> 3
<input type="checkbox" name="chk" value="4" /> 4
<input type="button" id="submit" value="Submit"/>
Then we can push the checked checkboxes to an action method using AJAX POST as shown below -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$("#submit").click(function () {
var vals = [];
$('input:checkbox[name=chk]:checked').each(function () {
vals.push($(this).val());
});
$.ajax({
url: "/Home/GetAttendeeJson",
type: "post",
dataType: "json",
data: JSON.stringify({ checkBoxValues: vals }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.success) {
}
else {
}
}
});
});
});
</script>
When we click on the button, the checked checkboxes can be obtained in following controller action -
public JsonResult GetAttendeeJson(int[] checkBoxValues)
{
//Code which creates the Json I need using the checkbox values.
return Json("true", JsonRequestBehavior.AllowGet)
}
View renders as follows where we can check/uncheck the checkboxes -
Then when you put a breakpoint and debug the code, output would be as shown below -
Try triggering ajax call periodically. So that without submitting form you can send it to your function.

Always returns a undefined value

I am using jQuery to send Ajax request to the server to save the values being input in the form. Below the section where I am stuck. The HTML is as
<span class="no-margin multiple Date_Off" style="margin-left: 104px;">
<input type="text" value="" /><input type="text" />
<input type="text" value="-" /><input type="text" />
<input type="text" /><input type="text" value="-" />
<input type="text" /><input type="text" /><input type="text" />
<input type="text" />
</span>
I have tried using jQuery to send the request. What I want to do is something like this
I want to save the values from the form, to the same Column_Name that the input fields have. In the multiple input fields I am not using input names. Instead I am using a classname which is identical to the Column_Name in the database.
For that, I am using $(this).parent().attr('class');. If I use this in an alert, it gives me the result without error. But if I use it in the code, it gives me undefined.
I want to append each input's value to the string to save it as a single string.
Here is what I tried so far
var input = $('input');
input.change(function () {
// Input click function...
if ($(this).parent().attr('class')
.replace(' multiple ', '')
.replace('no-margins', '') == 'Date_Off') {
// Date Time for the office work!
var value = '';
value = $(this).parent().find('input').each(function (index, ele) {
value += ele.val();
});
send_request('Date_Off', value);
// Below is the else condition, to execute only when the input is single
// Like a single string input and not like the one in image
// That's why I am using attr('name') for that.
} else {
send_request($(this).attr('name'), $(this).val());
}
});
But what it returns is always a undefined in the Query structure. Here is the function for that
function send_request(input_name, value) {
$.ajax({
url: '/ajax_requests/save_form',
data: 'input_name=' + input_name + '&form_id=' +
$('input[type=hidden]').val() + '&value=' + value,
error: function () {
$('.main-content').append(
'There was an error in request.
Please contact your website Developer to fix it.'
);
},
success: function () {
}
});
}
Image for the code execution
The input in focus was 1. Date. And the console shows the Internal Server Error. Because jQuery sent the request with input_name=undefined which is not a Column_Name.
I have created a (Mini) fiddle for that: http://jsfiddle.net/afzaal_ahmad_zeeshan/EHWqB/
Any help here?
For the fiddle that you posted, there were two errors. The first was you were calling ele.val(), but ele in this context is not a jQuery object - so you need to get the value property off of it. The second is that the jQuery each function operates on an array of objects and it's return value is that array of objects. You don't want your value, which should be a string, to be accepting that return value. Here is an updated, working fiddle
input.change(function () {
// Input click function...
var value = '';
$(this).parent().find('input').each(function (index, ele) {
value += ele.value;
});
send_request('Date_Off', value);
});
In this line you're trying to get the name of the input
send_request($(this).attr('name'), $(this).val());
I don't see a "name" attribute anywhere in your code, I think what you want is to get the class of the parent instead?
send_request($(this).parent().attr('class'), $(this).val());

jQuery: How to submit an array in a form

I have the following form. Each time the users clicks add_accommodation I want to add to an array that I will return to the end point (http://server/end/point).
<form action="http://localhost:3000/a/b/c" method="post">
<div>
<input type="hidden" id="Accommodation" name="accommodation"><div>
</div>
</form>
<div id="accommodation_component">
<div>
<label for="AccommodationType">Type:</label>
<input type="number" step="1" id="accommodationType" name="accommodation_type" value="0">
</div>
<div>
<button type="button" id="add_accommodation">Add Accommodation</button>
</div>
</div>
<script>
$( document ).ready(function() {
$('#add_accommodation').click(function() {
make_accommodation(this);
});
});
function make_accommodation(input) {
var value = {
type : $("#AccommodationType").val(),
};
var accommodation = $('#Accommodation').attr('id', 'accommodation');
accommodation.push(value);
console.log(accommodation);
}
</script>
At my end point I want the result to be and array (accommodation = [{1},{2},{3},{4}]). How can I do this?
Give the form an id, and just append a new hidden(?) input that has a name that has [] at the end of it, it will send the values as an array to the server.
HTML
<form id="myform" ...>
Javascript
function make_accommodation(){
var newInput = $("<input>",{
type:"hidden",
name:"accommodation[]",
value: {
type: $("#AccommodationType").val()
}
});
$("#myform").append(newInput);
}
Also you list the output as [1,2,3,4] but your code shows you setting the value as an object with a property type and setting it to the value of the accommodation input, i am going to assume that was a mistake. If I am mistaken just modify the value property in the code above.
Also in your code you change the id of the input, not sure why you were doing that as it serves no purpose and would have made your code error out so i removed it.
EDIT
Since you are wanting to send an array of objects, you will have to JSON.stringify the array on the client end and decode it on the server end. In this one you do not need multiple inputs, but a single one to contain the stringified data.
var accommodationData = [];
function make_accommodation(){
accommodationData.push({
type: $("#AccommodationType").val()
});
$("#accommodation").val( JSON.stringify(accommodationData) );
}
Then on the server you have to decode, not sure what server language you are using so i am showing example in PHP
$data = json_decode( $_POST['accommodation'] );
If you are using jQuery's ajax method you could simplify this by sending the array data
jQuery.ajax({
url:"yourURLhere",
type:"post"
data:{
accomodation:accommodationData
},
success:function(response){
//whatever here
}
});
Add antorher hidden field in form
<input type="hidden" name="accommodation[]"> // click1
<input type="hidden" name="accommodation[]"> // click2
...
<input type="hidden" name="accommodation[]"> // clickn
Then when you submit form on server you will have array of accommodation.
JS part :
function make_accommodation() {
$(document.createElement('input'))
.attr('type', 'hidden')
.attr('name', 'accommodation[]')
.val($("#AccommodationType").val())
.appendTo('form');
}
on server(PHP) :
print_r($_POST['accommodation']);
Since you're using jQuery you can create a function which creates another hidden field, after clicking on the button
<div id='acommodation-wrapper'></div>
<button type="button" id="add_accommodation" onclick="addAnother()">Add Accommodation</button>
<script type="text/javascript">
function addAnother(){
var accWrapper = $('#accommodation-wrapper');
var count = accWrapper.children().length;
var div = "<input type=\"hidden\" class=\"accommodation-"+count+"\" name=\"accommodation["+count+"]\"></div>";
accWrapper.append(div);
}
</script>

Categories

Resources