Can you help me on how to get the checkbox values to be a data array? I code like this, and don't get any output. Thanks for helping me.
In my html :
<input class="form-check-input delete-checkbox" type="checkbox" name="checkbox[]" id="checkbox" value="{{ $item->id }}"data-id="{{ $item->id }}">
In my JS:
function multiple_delete(id) {
const selected = [];
$(".form-check input[type=checkbox]:checked").each(function () {
selected.push(this.value);
});
if (selected.length > 0) {
dataid = selected.join(",");
$.ajax({
url: "multiple-delete",
type: "POST",
data: +dataid,
success: function (data) {
if (data["success"]) {
alert(data["success"]);
} else {
alert(data["error"]);
console.log(data);
}
},
error: function (data) {
alert(data.responseText);
},
});
}
}
My output :
First, you are using the wrong selector. You should change .form-check in the javascript to .form-check-input or .delete-checkbox. Also you can easily get values of the selected checkboxes using jquery's .map() method.
Change your javascript code to something like this
function multiple_delete(id) {
const selected = $(".delete-checkbox:checked").map((i, el) => el.value).get();
if (selected.length > 0) {
$.ajax({
url: "multiple-delete",
type: "POST",
data: selected.join(","),
success: function (data) {
if (data["success"]) {
alert(data["success"]);
} else {
alert(data["error"]);
console.log(data);
}
},
error: function (data) {
alert(data.responseText);
},
});
}
}
Related
I'm trying to make it so that when my ajax call is returned with an object/array, I can match up the results to checkboxes so that if there is a match I auto check the boxes
Here are my checkboxes
<input type="checkbox" name='Magazine' data-md-icheck />
<input type="checkbox" name='Website' data-md-icheck />
<input type="checkbox" name='Advertisement' data-md-icheck />
Now my ajax call is successful
I get back:
0: {}
type: "Magazine"
1: {}
type: "Website"
so in my ajax success, what I would like to do is take any result in that object, whether just one or all 3, and if the type matches the 'name' of the checkbox I want to check that box.
Here is my function that makes the successful ajax call. I just can't figure out a way to loop the return that I get so that I can match up any result that comes through
function getDetails(ID) {
console.log(ID);
$.ajax({
url: "/details",
data: {ID:ID},
_token: "{{ csrf_token() }}",
type: "POST",
success: function (data) {
},
});
};
So in this case, how would I modify my ajax success to check the magazine and website boxes?
Here is a pure JS and simple solution to this:-
// Assuming you get the response as an array of objects, which has a key as type
success: function (data) {
data.forEach(obj => {
let ele = document.getElementsByName(obj.type)[0];
if(ele) {
ele.checked = true;
}
});
}
This is how I would tackle it:
function getDetails(ID) {
console.log(ID);
$.ajax({
url: "/details",
data: {ID:ID},
_token: "{{ csrf_token() }}",
type: "POST",
success: function (data) {
for(var i=0;i<data.length;i++){
var item = data[i].type;
var checkbox = $('input[name="'+item+'"]);
if (checkbox.length){
checkbox.prop('checked', true);
}
}
},
});
};
Assume the result is pure text exactly the same as you provided (ES6+)
let a = 'result...'
['Magazine', 'Website', 'Advertisement'].filter(item => a.indexOf(item) != -1).forEach(item => {
let inputs = document.getElementsByName(item)
if (inputs.length > 0)
inputs[0].checked = true
})
<select id="multi-select-demo" multiple="multiple">
</select>
in below code we want to assign dynamic options values through ajax but it's not working
$.ajax({
type: 'POST',
url: 'get_checkparishdata',
data: { "campids": optionValue },
success: function (data2) {
new_data2 = data2;
if (new_data2 == '<option>No Record Found</option>') {
$(".bootparish").html(new_data2);
$("#multi-select-demo").html(new_data2);
$('#multi-select-demo').multiselect();
} else {
$(".bootparish").html(new_data2);
$("#multi-select-demo").html(new_data2);
}
}
});
//want to assign dynamic option value
$option_parish = '';
foreach($datapar as $Jurisdiction_parish)
{
$option_parish.='<option value="'.$Jurisdiction_parish.'"
selected>'.$Jurisdiction_parish.'</option>';
}
return $option_parish;
I have to return a return a multidimensional associative arrays from PHP page for a jQuery AJAX function.
This is my PHP page called 'seachsongs.php'
<?php
$brano = $_POST['brano'];
$sql = "SELECT Titolo, Autore FROM Brani WHERE Titolo = '$brano';";
$ris = $conn->query($sql);
while ($row = $ris->fetch_array()) {
$arr[] = $row;
}
echo json_encode(array('data' => $arr));
?>
This is my jQuery AJAX function
$(document).ready(function () {
$('#nBrano').keyup(function () {
nomeBrano = $(this).val();
$.ajax({
type: "POST",
data: {brano: nomeBrano},
url: "searchsong.php",
success: function (data) {
document.write(data);
//alert("Prova" + data['data'][0]["Titolo"]);
/*if (msg != 'null') {
$('#similarSongs').css('display', 'block');
/*$.each(prova, function (key1, value1) {
$.each(value1['two']['three'], function (key1, value1) {
document.write('test');
});
})
$('#similarSongs table').html(tabella);
}
if (msg == 'null') {
$('#similarSongs table').html("Nessun brano simile trovato");
$('#similarSongs').css('display', 'block');
}*/
},
error: function () {
//alert('errore');
}
});
});
});
How can I access to array data from jQuery? What is the correct statement?
alert(data)
print this
{"data":[{"0":"Animals","Titolo":"Animals","1":"Martin Garrix","Autore":"Martin Garrix"},{"0":"Animals","Titolo":"Animals","1":"Maron V","Autore":"Maron V"}]}{"data":[{"0":"Animals","Titolo":"Animals","1":"Martin Garrix","Autore":"Martin Garrix"},{"0":"Animals","Titolo":"Animals","1":"Maron V","Autore":"Maron V"}]}
PS: sorry form my bad english.
I've set the data type of this request to be json, so the response returned should be a json object. You can access it by this way:
$(document).ready(function () {
$('#nBrano').keyup(function () {
nomeBrano = $(this).val();
$.ajax({
type: "POST",
data: {brano: nomeBrano},
url: "searchsong.php",
dataType:'json',
success: function (response) {
for(var i=0; i<response['data'].length; i++){
console.log(response['data'][i][/*your_target_index*/]);
}
},
error: function () {
//alert('errore');
}
});
});
});
see more about ajax
I have class :
public JsonResult refreshMap(int time)
{
// Some code before
List<User> lista = new List<User>();
lista.Add(usr11);
lista.Add(usr22);
return Json(lista, JsonRequestBehavior.AllowGet);
}
And view :
<div id="PersonList"></div>
<input type="radio" name="time" value="5">Last 5min
<input type="radio" name="time" value="15">Last 15min
And the attached JS :
$(document).ready(function () {
$(':radio[name="time"]').change(function () {
$.ajax({
url: '/Connection/refreshMap',
cache: false,
dataType: "JSON",
data: {
time: $(':radio[name="time"]:checked').val()
},
success: function (data) {
$.each(data, function (index, value) {
$("#PersonList").append(value.Email);
});
}
});
return false;
});
});
And I want do this : when i checked radio I use method and I get data from controller and I want display this collection. But my function in ajax doesn't work. But when I return in method refreshMap only one object: [...] return Json(usr11, JsonRequestBehavior.AllowGet);
And if I change my ajax function like below, this work !
$(document).ready(function () {
$(':radio[name="time"]').change(function () {
$.ajax({
url: '/Connection/refreshMap',
cache: false,
dataType: "JSON",
data: { time: $(':radio[name="time"]:checked').val() },
success: function (data) {
$("#PersonList").append(data.Email +"</br>");
}
});
return false;
});
});
Have you idea what I can repair it?
data comes wrapped in 'd', by using $each you seem to enter the data object but in the second one it does not 'project' the values.
i usually do if(data.d){...} just to make sure the data will not shortcircuit my code, or the absence of it to be concrete.
Will also look at what type is 'Email' and how it serialised.
First of all i am not good enough in js.
I have two function in a page and i have to call another function in an existing function.
I have=>
function suggest1(inputString){
if(inputString.length == 0) {
$('#suggestions1').fadeOut();
}
else{
$('#p_name').addClass('load');
$.post("autosuggest.php", {queryString: ""+inputString+""}, function(data)
{
if(data.length >0)
{
$('#suggestions1').fadeIn();
$('#suggestionsList1').html(data);
$('#p_name').removeClass('load');
}
});
}
}
function fill1(thisValue) {
$('#p_name').val(thisValue);
$('#p_nameA').val(thisValue);
setTimeout("$('#suggestions1').fadeOut();", 100);
}
This is an auto suggest function
Ineed to call function which is bellow, which can use the value of $('#p_name').val(thisValue); in var name_tast. Is it possible or not?
function getAccaounce()
{
var name_tast = document.getElementById("p_nameA").value;
$.ajax({
type: "POST",
url: 'ajax_accaounce.php',
dataType: 'json',
data: {
'p_nameA': name_tast,
},
success: function(data)
{
$('#available1').html(data.message1);
$('#price1').html(data.message2);
}
});
}
Thanks in advance.