I am have the below checkboxes and I want to pass the checked values to an array so that I can do an ajax post. However, I am hitting an error and I am not sure where I went wrong...
How do I pass the values into the array and how do I retrieve them?
HTML
<input type="checkbox" name="newCheckboxes" value="1" />
<input type="checkbox" name="newCheckboxes" value="2" />
<input type="checkbox" name="newCheckboxes" value="3" />
Script (not working)
var allFields = $( [] );
$("#newCheckboxes:checked").each(function() {
allFields.add( $(this).val() );
});
$.ajax(
{
type:"POST",
url: "PostedHere",
data:{
checkedValues: allFields
}
});
You only need:
$.ajax({
type:"POST",
url: "PostedHere",
data: { checkedValues: $("#newCheckboxes:checked").serialize() }
});
// checkedValues: "newCheckboxes=1&newCheckboxes=2" etc..
Using karim79 code idea:
$.post('URL', $('[name="newCheckboxes"]:checked').serializeArray(), function(data){
//data
});
What I prefer to do is: Create a new Object and add all checkboxes 'Value' and 'Ischecked' to an array (access), then pass it to page by Json:
$(document).ready(function () {
$("#btnSave").click(function () {
event.preventDefault();
$("#newCheckboxes").each(function () {
var data= new Object()
var access = new Array();
access.ChValue = $(this).attr("value");
if ($(this).attr("checked") == "checked") access.ChChecked = true;
data.push(access);
});
$.ajax({
type: 'POST',
url: '#Url.Content("~/URLofPage")',
data: $.json.encode(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
});
});
please do not forgot to add Json reference to your page:
<script src="../../../Scripts/jquery.json.js" type="text/javascript"></script>
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
})
I'm trying to pass a checkbox array into an AJAX call for a search form im working on:
HTML:
<form id="searchForm">
<input type="checkbox" class="typesSearch" name="types[]" value="Fundraiser" checked /> Fundraiser<br>
<input type="checkbox" class="typesSearch" name="types[]" value="Conference" checked /> Conference<br>
</form>
JavaScript:
var types = [];
var eventTypes = document.forms['searchForm'].elements[ 'types[]' ];
for (var i=0, len=eventTypes.length; i<len; i++) {
if (eventTypes[i].checked ) {
types.push($(eventTypes[i]).val());
}
}
$.ajax({
url: "https://www.example.com/search.php",
method: "post",
data:{
eventname: eventname,
types: types
},
dataType:"text",
success:function(data)
{
$('#eventsList').html(data);
$('#eventsList').slick($opts);
}
});
PHP:
$event_types = $_POST['types'];
The types array is fine on the javascript side, its when it hits the PHP side that $_POST['types'] is read as being empty.
Why is it that $_POST['types'] is read as empty? Is there something in the AJAX call where I need to define that I'm passing in an array instead of a string?
Try to use the following at "data":
$.ajax({
url: "https://www.example.com/search.php",
method: "POST",
data:{
eventname: eventname,
types: JSON.stringify(types)
},
dataType:"text",
success:function(data)
{
$('#eventsList').html(data);
$('#eventsList').slick($opts);
}
});
With this, the types is a string and you need to parse it to array object on PHP side.
On server side, you can use the following code to get the array. The $item[0]
$event_types = $_POST['types'];
$item = (json_decode(stripslashes($event_types)));
You need to serialize your array in order to receive it in $_POST, so your ajax should look like:
$.ajax({
url: "https://www.example.com/search.php",
method: "post",
data:{
eventname: eventname,
types: JSON.stringify(types) //serializied types[]
},
dataType:"text",
success:function(data)
{
$('#eventsList').html(data);
$('#eventsList').slick($opts);
}
});
You might want to try this solution too:
JS:
data: { typesArray: types }
PHP:
$types = $_REQUEST['typesArray'];
I have a form with two inputs (later more inputs). One input is a text input and the second one is a checkbox. I would like to send these two inputs with $.ajax.
I created an Object formData with one input. The second one I would like to append to the Object if the checkbox is active or not.
Unfortunately, I can't pass the Object because of a wrong format.
My Code:
<form id="myForm">
<input type="text" name="search_text" id="search_text" placeholder="Search by a name">
<input type="checkbox" name="exact" value="Exact">Exact
</form>
<br>
<div id="result"></div>
<script type="text/javascript">
$(document).ready(function(){
$('#myForm').on('change', ':checkbox', function(){
if($(this).is(':checked')) {
console.log($(this).val() + ' is now checked');
}
else {
console.log($(this).val() + ' is now unchecked');
}
});
var formData = {'qry':search};
$('#search_text').on('keyup', function(e){
e.preventDefault();
var search = $(this).val();
$('#result').html('');
$.ajax({
url:"fetch.php",
method: "POST",
data: formData,
dataType: "text",
success:function(data) {
$('#result').html(data);
}
});
});
});
</script>
You need to serialise the form data and then add more data if required:
var data = $('#myForm').serializeArray();
data.push({name: 'sample', value: "something_more"});
Your ajax should then be something like:
var data = $('#myForm').serializeArray();
data.push({name: 'sample', value: "something_more"});
$.ajax({
url:"fetch.php",
method: "POST",
data: data,
dataType: "text",
processData: false,
success:function(data) {
$('#result').html(data);
}
});
I am trying to test a simple FormData object but its not working at all. jsfiddle: https://jsfiddle.net/8j80898h/
html code:
<form id="createForm" name="createForm" novalidate enctype="multipart/form-data">
<input type="hidden" name="name" value="Name1" />
<input type="file" name="file" />
<input type="button" id="submitIt" value="Submit" />
</form>
js:
$(document).ready(function() {
$('#submitIt').click(function() {
var fd = new FormData($('#createForm')[0]);
fd.append( 'name', $('input[name=name]').val());
$.ajax({
url: url,
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
});
});
Server is always getting null values for name and file
FormData has a get method you should use:
$(document).ready(function() {
$('#submitIt').click(function() {
var d = new FormData($('form')[0]);
alert(d.get('name'));
});
});
read more in MDN: https://developer.mozilla.org/en-US/docs/Web/API/FormData/get
rather than making an FormData object you can access elements within an form like the code below shows :)
$(document).ready(function() {
$('#submitIt').click(function() {
var d = $('form').toArray();
alert(d[0].name);
});
});
I am trying to make an autocomplete widget that will display item's codes returned from a database.
I have successfully made it so my database will return the appropriate JSON response.
The problem now is I don't know why the drop-down list doesn't show up.
Here's the code down below:
<input type="text" id="search" class="form-control" placeholder="">
<form action="post" action="" id="spareParts" class="spareparts">
</form>
$('#search').keyup(function(event) {
var search = $(this).val();
if($.trim(search).length){
var arr = [];
$.ajax({
url: 'get_spareparts',
type: 'POST',
dataType: 'JSON',
data: {item: search},
success: function (data) {
arr = $.parseJSON( data );
console.log(arr);// CONSOLE.LOG WORKS WELL
//[Object { id="1", value="25.00", desc="Fuel pump", more...}]
// AUTOCOMPLETE DOESN'T WORK
$('#spareParts').autocomplete({
minLength:0,
source: arr
});
}
});
}
});
The autocomplete with AJAX loaded data should be configured differently. source property can be a function which accepts a callback parameter. You should feed this callback with data loaded from server.
Also you don't need to bind keyup event manually. Your code will become:
$('#search').autocomplete({
minLength: 0,
source: function(request, response) {
$.ajax({
url: 'get_spareparts',
type: 'POST',
dataType: 'JSON',
data: {item: request.term}
}).done(function(data) {
response(data.map(function(el) {
return {
value: el.value,
label: el.desc
};
}))
});
}
});