Currently, my checkbox values is being stored as ["A","B","C"] into the database when I have only selected one option (eg C). Also, I have another question - is there any way possible to store it as ABC instead?
$(document).ready(function() {
"use strict";
var role;
});
function savenewuser() {
var url = serverURL() + "/newadmin.php";
checklist = new Array();
$('input:checkbox[name="roles[]"]').each(function() {
checklist.push($(this).val());
});
role = JSON.stringify(checklist);
$.ajax({
url: url,
type: 'GET',
data: {
"role": role,
},
success: function(arr) {
_getNewUserResult(arr);
},
error: function() {
alert("error");
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><label for="rights">Rights</label></div>
<input type="checkbox" name="roles[]" value="A">Bookings
<input type="checkbox" name="roles[]" value="B">Incident Booking
<input type="checkbox" name="roles[]" value="C">Edit User
You're saving all the checkboxes:
$('input:checkbox[name="roles[]"]').each(function() {
checklist.push($(this).val());
});
Try saving :checked ones only:
$('input:checkbox[name="roles[]"]:checked').each(function() {
checklist.push($(this).val());
});
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 have been having a little problem. I am trying to create a filter for my database. So far I have come up with this:
Blade File:
<input type="text" class="form-control" id="search" name="search" placeholder="Name, NORAD or ID"></input>
<select name="filtername" id="filtername">
<option value="none"></option>
<option value="Falcon">Falcon</option>
<option value="rb">R/B</option>
</select>
Javascript AJAX Call:
$(document).ready(function() {
$('#search').on('keyup', function() {
$value = $(this).val();
delay(function() {
if ('#search'.length > 3) {
$.ajax({
type: 'get',
url: '{{$launchsitename->site_code}}',
data: {
'search': $value
},
success: function(data) {
$('#launchsatdisplay').html(data);
}
});
}
}, 300);
});
$("#filtername").change(function() {
var filtername = $(this).val();
var dataString = "filtername=" + filtername;
$.ajax({
type: "get",
url: "{{$launchsitename->site_code}}",
data: {
'search': dataString
},
success: function(data) {
$('#launchsatdisplay').html(data);
}
});
});
});
Controller:
if ($request->ajax())
{
$output="";
$launchsitesatellite = DB::table('satellites')
->where(function($q) use ($request) {
$q->orWhere('satname','LIKE','%'.$request->search.'%')
->orWhere('norad_cat_id','LIKE','%'.$request->search.'%')
->orWhere('object_id','LIKE','%'.$request->search.'%');
})
->where('site', $site_code)->get();
if ($launchsitesatellite)
{
$output .='<tr>'.
'<th>'.'Satellite Name'.'</th>'.
'<th>'.'NORAD ID'.'</th>'.
'<th>'.'Object Type'.'</th>'.
'<th>'.'Launch Date'.'</th>'.
'<th>'.'Country'.'</th>'.
'<th>'.'Object ID'.'</th>'.
'<tr>';
foreach ($launchsitesatellite as $key => $launchsitesatellites) {
$output .='<tr>'.
'<td>'.$launchsitesatellites->satname.'</td>'.
'<td>'.$launchsitesatellites->norad_cat_id.'</td>'.
'<td>'.$launchsitesatellites->object_type.'</td>'.
'<td>'.$launchsitesatellites->launch.'</td>'.
'<td>'.$launchsitesatellites->country.'</td>'.
'<td>'.$launchsitesatellites->object_id.'</td>'.
'</tr>';
}
}
return $output;
}
else {
$launchsitesatellite = DB::table('satellites')->where('site', $site_code)->Paginate(40);
return view('pages/launchsite-filter', compact('launchsites', 'launchsitesatellite'));
}
This code is for making an AJAX call to my controller and getting the results from the database. The code posted above works perfectly for the input. I am able to search the database with ease. The only problem is with the select. Whenever I select an option, it returns no results. I am guessing there is something wrong with the way I programmed the select in my controller, as I don't think the Javascript would be causing the problem.
The select should be reading the satname column in my database called satellites and returning the filtered results.
Would somebody be able to shed some light on why the select is not working or where the error in my code is?
modify your ajax call code for select box as below
$("#filtername").change(function() {
var dataString = $(this).val();
$.ajax({
type: "get",
url: "{{$launchsitename->site_code}}",
data: {
'search': dataString
},
success: function(data) {
$('#launchsatdisplay').html(data);
}
});
});
I have a form where I have countries list in checkbox format to be inserted into database. Say for example:
<input type="checkbox" name="country[]" value="Afghanistan" checked>Afghanistan<br>
<input type="checkbox" name="country[]" value="Albania" checked>Albania<br>
<input type="checkbox" name="country[]" value="Algeria" checked>Algeria<br>
<input type="checkbox" name="country[]" value="American Samoa" checked>American Samoa<br>
<input type="checkbox" name="country[]" value="Andorra" checked>Andorra<br>
<input type="checkbox" name="country[]" value="Angola" checked>Angola<br>
<input type="checkbox" name="country[]" value="Anguilla" checked>Anguilla<br>
I want to insert this into database using ajax. I could have easily done this through normal same page PHP post. But when sending data with ajax to other page for processing I am confused on how to send. Once it sends all the selected checkbox values perfectly then all the rest is onto me.
My AJAX script
$("#submit").click(function() {
var dataString = {
clicks: $("#clicks option:selected").data("value"),
country: $("input[name=country").data("value") // tried using this and input[name=country[]] but they did not work.
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to purchase this advertisement?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType : "json",
url: "add-ptc-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#loading-rent").hide();
$("#submit").show();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
}
}
});
return false;
});
});
I have put a check on the processing page where if the country value is empty return error like:
if($country == ''){
echo "No countries selected. Please select at least one country.";
}
No matter if I select one or all countries still I get this error response back. What should I do to send these checkbox data with ajax?
Try
var countries = {};
$('input[name^="country"]').each(function(){
countries[$(this).attr('value')] = $(this).is(":checked");
});
then post it to ajax data: countries or change the code to send only checked elements
Your PHP will receive an array so you can check
if(is_array($_POST['countries'])){
foreach($_POST['countries'] AS $country_name => $is_checked){
//do something...
}
}
You will want to switch your .data() to .val() on your input capture. Also change the name of the inputs to input[name=country\\[\\]]:checked.
# Use "e" as the event
$("#submit").click(function(e) {
# Use this function to stop the form
e.preventDefault();
# You could make a quick function to save all the countries
# You can actually feed other selectors into this as well, so
# it can do all your value retrievals, not just for countries
function getCountries(checkboxes)
{
var getVals = [];
$.each($(checkboxes),function(k,v) {
getVals.push($(v).val());
});
return getVals;
}
var dataString = {
clicks: $("#clicks option:selected").val(),
# Run the function to gather
# Note the name (escaped [] with :checked)
country: getCountries("input[name=country\\[\\]]:checked")
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to purchase this advertisement?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType: "json",
url: "add-ptc-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#loading-rent").hide();
$("#submit").show();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
}
}
});
});
I'm using materialize ui in an ASP.Net MVC application and I'm using an autocomplete control with dynamic data.
Here is my code,
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">textsms</i>
<input type="text" id="autocomplete-input" class="autocomplete">
<label for="autocomplete-input">Autocomplete</label>
</div>
</div>
</div>
</div>
This is the jquery ajax call,
$(function () {
$.ajax({
type: 'GET', // your request type
url: "/Home/GetData/",
success: function (response) {
var myArray = $.parseJSON(response);
debugger;
$('input.autocomplete').autocomplete({
data: {
"Arizona (1)": null,
"Florida (2)": null,
"Georgia (3)": null,
"Hawaii(4)": null,
"Idaho (5)": null,
"Illinois (6)": null
}
});
}
});
});
It can accept data only in this format and this is my response,
"[["Arizona (1)"],["Florida (2)"],["Georgia (3)"],["Hawaii (4)"],["Idaho (5)"],["Illinois (6)"]]"
How do I convert my response into the format that autocomplete understands?
Using ajax API call for materializecss input autocomplete
I have modified as below to obtain autocomplete input for Countries.
You can get the list of country names from API https://restcountries.eu/rest/v2/all?fields=name
$(document).ready(function() {
//Autocomplete
$(function() {
$.ajax({
type: 'GET',
url: 'https://restcountries.eu/rest/v2/all?fields=name',
success: function(response) {
var countryArray = response;
var dataCountry = {};
for (var i = 0; i < countryArray.length; i++) {
//console.log(countryArray[i].name);
dataCountry[countryArray[i].name] = countryArray[i].flag; //countryArray[i].flag or null
}
$('input.autocomplete').autocomplete({
data: dataCountry,
limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
});
}
});
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s12">
<label for="country">Autocomplete</label>
<input type="text" id="country" class="autocomplete">
</div>
</div>
</div>
</div>
Good day. I can suggest a little different approach. Materialize autocomplete has method
updateData
So if we want to get ajax to load data, we may add event listener to input field
$(".autocomplete").each(function () {
let self = this;
$(this).autocomplete();
$(this).on("input change", function () {
$.ajax({
url: '/source/to/server/data',
type: 'post',
cache: false,
data: {"some": "data"},
success: function (data) {
data = JSON.parse(data);
$(self).autocomplete("updateData", data/*should be object*/);
},
error: function (err) {
console.log(err);
}
});
});
});
Not ideal for different data sources, but may be a starting point.
Not very fancy, but give it a try:
$(function () {
$.ajax({
type: 'GET', // your request type
url: "/Home/GetData/",
success: function (response) {
var myArray = $.parseJSON(response);
var dataAC = {};
for(var i=0;i<myArray[0].length;i++){
eval("dataAC." + myArray[0][i] + " = null;");
}
debugger;
$('input.autocomplete').autocomplete({
data: dataAC
});
}
});
});
Try to convert your response through this way, in your case you don't need the first line of code.
var responseData = JSON.parse(`[["Arizona (1)"],["Florida (2)"],["Georgia (3)"],["Hawaii (4)"],["Idaho (5)"],["Illinois (6)"]]`);
var acArray = [];
var acData = {};
responseData.forEach(res => {
acArray.push(res.join())
})
acArray.forEach(acObj => {
acData[acObj] = null;
})
console.log(acData)
you can easily achieve the autocomplete functionality using the Devberidge plugin.
Get Devbridge plugin using https://github.com/devbridge/jQuery-Autocomplete
<script type="text/javascript">
$(document).ready(function() {
$("#country").devbridgeAutocomplete({
//lookup: countries,
serviceUrl:"getCountry.php", //tell the script where to send requests
type:'POST',
//callback just to show it's working
onSelect: function (suggestion) {
// $('#selection').html('You selected: ' + suggestion.value + ', ' + suggestion.data);
},
showNoSuggestionNotice: true,
noSuggestionNotice: 'Sorry, no matching results',
});
});
</script>
Here the getCountry.php file returns the JSON data.
For more info visit https://ampersandacademy.com/tutorials/materialize-css/materialize-css-framework-ajax-autocomplete-example-using-php
My requirement is to show few options when user input some characters (minimum 3) in one of input field which might be added dynamically too.
I can not load data at page loading at beginning because data is huge. There is an ajax call to get that filtered data.
The issue what I am getting is Expected identifier error on page loading at line# 2. So, could you please tell what is wrong with the below code?
$(document).on('keydown.autocomplete', 'input.searchInput', function() {
source: function (request, response) { // Line # 2
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getNames.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
How about using another approach: initialize the autocomplete when you create the input:
$(function() {
// settings for each autocomplete
var autocompleteOptions = {
minLength: 3,
source: function(request, response) {
$.ajax({
type: "GET",
url: "getNames.html",
data: { name: request.term },
success: function(data) {
response(data);
}
});
}
};
// dynamically create an input and initialize autocomplete on it
function addInput() {
var $input = $("<input>", {
name: "search",
"class": "searchInput",
maxlength: "20"
});
$input
.appendTo("form#myForm")
.focus()
.autocomplete(autocompleteOptions);
};
// initialize autocomplete on first input
$("input.searchInput").autocomplete(autocompleteOptions);
$("input#addButton").click(addInput);
});
<form id="myForm" name="myForm" method="post">
<input id="addButton" type="button" value="Add an input" />
<input name="search" class="searchInput" maxlength="20" />
</form>
jsFiddle with AJAX
The method where I am adding new input field there writing below code.
function addInput(){
// Code to append new input filed next to existing one.
$("table").find('input[id=clientId]:last').autocomplete({
source: function (request, response) {
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getName.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},
error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
}
And some where in other js which will be used to all other (static) input fields below code is used.
jQuery("input.searchInput").autocomplete({
source: function (request, response) {
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getName.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},
error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
Note :- For any autocomplete requests in dynamically added input fields, AutoComplete code of addInput() function will be called.
Thanks to #Salman and this post Enabling jQuery Autocomplete on dynamically created input fields to give me an idea.
Try this.
$("#autocompleteElement").autocomplete({
source:function (data, response) {
$ajax({
url:'your/url?name='+data.term,
success:function(data){
response(data);
}
})
}
});
This code based on jquery UI autocomplete.