I want to do an ajax request to update the status of an item, but for one or many selected item.
So how can I post all the selected checkbox items to process it on the handle page?
Here is some code I use., but it will only post one item to the process page.
<td>
<input type="checkbox" class="select-all" name="item[]" id="item[78]">
</td>
<td>
<input type="checkbox" class="select-all" name="item[]" id="item[182]">
</td>
And the javascript
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}}"
}
});
var formData = {
item: $('input[name=item\\[\\]]').val(),
}
var type = "POST";
var my_url = "/posturl";
$.ajax({
type: type,
url: my_url,
data: formData,
success: function (data) {
console.log(formData);
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
Assign the unique name to each checkbox
Put all checkboxes in a form tag (all input fields in a single form).
Use serialize() or serializeArray() for collecting data from form
store data in var formData
Code:
<form id="form-name">
<tr>
<td>
<input type="checkbox" name="item[1]">
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="item[32]">
</td>
</tr>
</form>
Javascript:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}}"
}
});
var formData = $('#form').serializeArray();
var type = "POST";
var my_url = "/posturl";
$.ajax({
type: type,
url: my_url,
data: formData,
success: function (data) {
console.log(formData);
},
error: function (data) {
console.log('Error:', data);
}
});
This will post an array of items to the url.
I did same thing in minor different way.
I got list of checkbox and names contain their id.
<input type="checkbox" class="bulkChecked" name="{{$value->id}}">
And Inside your event handler
var ids = [];
$(".bulkChecked:checked").each(function () {
ids.push($(this).attr("name"));
});
So at this point you have got ids of checked boxes. No you can pass 'ids' array with your ajax call
Related
Hello guys im currently learning on how to send data from HTML to Django backend using Ajax.
I have this HTML
<div class="form-row">
<input type="checkbox" name="car-checkbox[]" value="Audi" id="chck1">
<input type="checkbox" name="car-checkbox[]" value="BMW" id="chck2">
<input type="checkbox" name="car-checkbox[]" value="Lambo" id="chck2">
<input id="submit-car" type="button" value="Submit">
</div>
and then to send the data i use this code (Ajax)
$('#submit-car').click(function () {
const data = {user_id: user_id}
$.ajax({
type: 'POST',
url: '/submit-car/',
data: data,
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function (data) {
$('#submit-form-field').prop('disabled', true);
location.reload();
alert("Submit OK!");
}
});
});
and then on the Django side i try to get the checked checkbox
def insert_car_to_db(self, request):
cars = request.POST.getlist('car-checkbox[]')
print(cars)
Weirdly enough when i try to get the checked data, i keep getting [] value,
where did i miss ? am i misunderstand something?
P.S
i followed this post
How to get array of values from checkbox form Django
$('#submit-car').click(function () {
const car_checkbox = [];
const user_id = "Some test UserId";
const csrftoken = "Provided CSRF TOKEN";
$("input[type=checkbox]:checked").each(function(){
car_checkbox.push($(this).val());
}); //STore the checkbox result in an array
const data = {"user_id": user_id, "car-checkbox": car_checkbox}
console.log(data);
$.ajax({
type: 'POST',
url: '/submit-car/',
data: data,
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function (data) {
$('#submit-form-field').prop('disabled', true);
location.reload();
alert("Submit OK!");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row">
<input type="checkbox" name="car-checkbox" value="Audi" id="chck1">
<input type="checkbox" name="car-checkbox" value="BMW" id="chck2">
<input type="checkbox" name="car-checkbox" value="Lambo" id="chck2">
<input id="submit-car" type="button" value="Submit">
</div>
So where you are sending the checkbox array value to backend /submit-car/ ?
what is user_id in your click evennt?
As you are using jquery so
$('#submit-car').click(function () {
const car_checkbox = [];
$("input[type=checkbox]:checked").each(function(){
car_checkbox.push($(this).val());
}); //STore the checkbox result in an array
const data = {"user_id": user_id, "car-checkbox": car_checkbox}
$.ajax({
type: 'POST',
url: '/submit-car/',
data: data,
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function (data) {
$('#submit-form-field').prop('disabled', true);
location.reload();
alert("Submit OK!");
}
});
});
# I just want to know how to send this array the controller by requete ajax
var dataPanier=[];
function addarray(objser)
{
dataPanier.push(objser);
}
$('.target').click(function() {
var btn_name=$(this).attr("name");
switch(btn_name) {
case 'FormPVC':
var dataformPVC = new FormData(),
form_data = $('#'+btn_name).serializeArray();
$.each(form_data, function (key, input) {
dataformPVC.append(input.name, input.value);
});
dataformPVC.append('Fichier', $('#File_PVC')[0].files[0]);
/* function addarray push dataform in array*/
addarray(dataformPVC);
break;
.
.
.
more . . .
I am attempting to send multiple forms data as an array by ajax to a Larave controller.
$.ajax({
type: 'POST',
url: 'lsitedevis',
data: array ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
$("#btnTest").click(function(){
var formData = $('#frm1, #frm2').serialize();
console.log(formData);
$.ajax({
method: 'POST',
url: 'lsitedevis',
data: formData ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="frm1">
<input name="n1" type="text"/>
<input name="n2" type="hidden" value="test2"/>
<input name="n3" type="hidden" value="test3"/>
</form>
<form id="frm2">
<input name="n1" type="text" />
<input name="n2" type="hidden" value="test2"/>
<input name="n3" type="hidden" value="test3"/>
</form>
<input type="button" id="btnTest" value="send"/>
As your already using jQuery for the AJAX request, you could use the serialize() function. This supports multiple form elements, so it is possible to do:
var formData = $('#form1, #form2').serialize();
$.ajax({
type: 'POST',
url: 'lsitedevis',
data: formData ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
You might want to ask yourself why you have multiple forms but submitting them all as a single request. If it's for visual purposes, it might be easier to have a single form and separate the contents using other markup elements such as a <fieldset> or <div>.
I have a Sudoku board generated with thymeleaf and I want to send all the tile values as a double array to a Spring controller or as a String.
<form class="box" id="sudokuBoard">
<table>
<tr th:each="row: ${board}">
<td th:each="value: ${row}">
<div th:switch="${value}">
<input th:case="0" style="width:30px;height:30px;text-align:center" type = "text" maxlength="1" value="0">
<input th:case="*" style="width:30px;height:30px;text-align:center;background-color:lightgreen" type = "text" th:value="${value}" readonly>
</div>
</td>
</tr>
</table>
<input type="submit"> Check Solution </input>
</form>
I've tried to use the serialize() function but it doesn't send anything or I'm doing something wrong.
<script>
$("#sudokuBoard").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
$.ajax({
type: "POST",
url: "/sudoku",
dataType: 'json',
data: form.serialize(),
success: function(msg)
{
console.log("data sent");
}
});
});
</script>
This is the Spring controller
#RequestMapping(value = "/sudoku", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
String checkBoardStatus(#RequestBody String jsonString){
System.out.println("json string: " + jsonString);
return "sudoku";
}
You can use this example, where success will be your callback method
$.ajax({
type: "POST",
url: url,
data: data,
success: function(result) {},
dataType: dataType
});
#RequestMapping(value = "/sudoku", method = RequestMethod.POST)
String checkBoardStatus(Map<String,Object> params){
System.out.println("Request Params: " + params);
return "sudoku";
}
User above code.. Try to use a DTO class to map request body instead of Map and do not use #RequestBody annotation
I have a form that I want to send its data to admin-ajax:
<form method="POST" id="form">
<input type="text" name="name">
<input type="number" name="phone">
<input type="email" name="email">
<textarea name="overview"></textarea>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
Javascript/jQuery code to send the data using Ajax:
document.getElementById('submit').addEventListener('click', function(e){
e.preventDefault();
var form_data = $('#form').serialize();
$.ajax('http://mywebsite.com/wordpress/wp-admin/admin-ajax.php', {
method: "POST",
data: form_data + {action: 'my_action'},
success: function (response) {
console.log(response);
},
error: function (err) {
console.log('Error:' + err);
}
});
});
Also tried formData:
var form_data = new FormData();
form_data.append('form', $('#custom').serialize());
form_data.append('action', 'my_action');
How to send the form data and the action my_action?
you need to change this line from data: form_data + {action: 'my_action'}, to data: {action: 'my_action', form_data:form_data},
jQuery(document).on("click","#submit", function(){
e.preventDefault();
var form_data =jQuery('#form').serializeArray();
jQuery.ajax('http://mywebsite.com/wordpress/wp-admin/admin-ajax.php', {
method: "POST",
data: {action: 'my_action', form_data:form_data},
success: function (response) {
console.log(response);
},
error: function (err) {
console.log('Error:' + err);
}
});
});
and change input type submit to button.
In general i prefer to use this way, like in your case you are using submit type button:
$(document).on('click', '#submit', function(){ // the id of your submit button
var form_data = $('#your_form_data_id'); // here is the id of your form
form_data.submit(function (e) {
var my_action = "my_action";
e.preventDefault();
$.ajax({
type: form_data.attr('method'), // use this if you have declared the method in the form like: method="POST"
url: form_data.attr('action'), // here you have declared the url in the form and no need to use it again or you can also use the path like in your code
data: form_data.serialize() +'&'+$.param({ 'my_action': my_action}), // here you are sending all data serialized from the form and appending the action value you assing when declare var my_action
success: function (data) {
// after the success result do your other stuff like show in console, print something or else
},
});
});
});
Hope it helps you. if anything is not clear feel free to ask, i try to explain in the comments.
You should just pass form to new FormData() so in your case when submitting the form just pass new FormData(e.target);
Hope it helps
The following code is my original code. In the code, I tried to post value of an input for each checkbox which is checked.
<tbody class="myFormSaldo">
<tr>
<td> <input name="checkbox['.$i.']" type="checkbox" value="'.$i.'" id="chb'.$ref.'" onchange="enableList(this);" class="chb_group" /> </td>
<td> <input name="items['.$i.']" type="text" readonly value="'.$obj->items.'" /> </td>
<td> <input name="size['.$i.']" type="text" readonly value="'.$obj->size.'Kg" /> </td>
<td> <input name="quantity['.$i.']" type="text" readonly value="'.$obj->myquantity.'" /> </td>
if($_SERVER["REQUEST_METHOD"] == "POST") {
foreach($_POST['checkbox'] as $i) {
$product_name=$_POST['items'][$i];
$product_size=$_POST['size'][$i];
The code above is working fine. It post the value of each inputs for each checkbox which were checked. For example; if there were three checkedbox which were checked and the form was submited, then it would post three arrays (3 loop) of : $product_name,$product_size,etc..
What I want now is to use Ajax. Like this:
var product_name= document.getElementById('product_name').value;
var product_size = document.getElementById('product_size').value;
$.ajax(
{
type: "POST",
url: "../actions/selectReferenceOrder.php",
data: product_name='+product_name+'&product_size ='+product_size ,
cache: false,
success:function(html)
{
document.getElementById('outputReference').innerHTML = html;
}
});
But it doesn't count or find the checkbox
So my question now is how to do the same as the php do with foreach($_POST['checkbox'] as $i) in ajax?
I am just a beginner in all of these things.
Thank you for any help.
You are using your product_name as a string, not as a variable:
Try this:
data: 'product_name='+product_name+'&product_size='+product_size,
Or, as Ghost sad in comments, use formdata.
var dataString = $('form').serialize();
and later, in the ajax:
data: dataString,
...
Try this...
<script>
$.ajax({
type: "POST",
url: "../actions/selectReferenceOrder.php",
data: "{'product_name':" + product_name + ", 'product_size':" + product_size+ "}",
cache: false,
dataType: "html"
success:function(html)
{
document.getElementById('outputReference').innerHTML = html;
}
});
</script>
Try this
Ajax is simplified check here
var data = $('form').serialize();
$.post( "../actions/selectReferenceOrder.php", { name: data}).done(function( data ) {
alert( "Data Loaded: " + data );
});
OR
$.post( "../actions/selectReferenceOrder.php", { product_name: product_name, product_size : product_size }).done(function( data ) {
alert( "Data Loaded: " + data );
});