How to make comparison using JSON/jQuery and PHP data - php

I am currently using a JQuery code and a JSON file to load cities in a select> according to the chosen state/province. The JQuery is below.
$(document).ready(function() {
$.getJSON('../../../js/statesCities.json', function(data) {
var items = [];
var options = '<option value="">Selecione</option>';
$.each(data, function(key, val) {
options += '<option value="' + val.sigla + '">' + val.sigla + '</option>';
});
$("#estados").html(options);
$("#estados").change(function() {
var options_cidades = '<option value="">Selecione</option>';
var str = "";
$("#estados option:selected").each(function() {
str += $(this).text();
});
$.each(data, function(key, val) {
if (val.sigla == str) {
$.each(val.cidades, function(key_city, val_city) {
options_cidades += '<option value="' + val_city + '">' + val_city + '</option>';
});
}
});
$("#cidades").html(options_cidades);
}).change();
});
});});
The JSON code I am using: https://gist.github.com/letanure/3012978
And the HTML selects:
<div>
<b>Estado:</b>
<select id="estados" class="form-control" name="estadoCliente" required>
<option value="">Selecione</option>
</select>
</div>
<div>
<b>Cidade:</b>
<select id="cidades" class="form-control" name="cidadeCliente" required>
<option value="">Selecione</option>
</select>
</div>
In fact, this code works just fine. But when I want to fill a form using PHP data, the code doesn't help. (The registration page is the same as editing. On the edition page, PHP loads user's information). If all the states and cities were pre-loaded in the HTML (Have all options typed), in order to check which state and city are in the database, I would use an inline PHP's if, considering the variable $state as the state of any user who filled in this form.
<option <?php echo $state=='AB'?'selected': ''?>>AB</option>
But It can't be used because the function $.each won't accept the variables from PHP. So, my question is how can I do this verification to each option, having the state and city saved in a database? I will use this code to load the data of a user, so I can edit information more easily.
PS: I don't know how I could better describe this question on the title.

Because you're loading the data on the frontend you will need to store the backend values somewhere, then once the data has loaded, use the JS to compare and select the correct option.
In your html you could do (supposing you're not using a templating engine):
<div>
<b>Estado:</b>
<select id="estados" class="form-control" name="estadoCliente" initial-val="<?php $estado; ?>" required>
<option value="">Selecione</option>
</select>
</div>
<div>
<b>Cidade:</b>
<select id="cidades" class="form-control" name="cidadeCliente" initial-val="<?php $cidade; ?>" required>
<option value="">Selecione</option>
</select>
</div>
Above you should see the use of initial-val="...", you can call this whatever you want. You will use these values when the data loads...
So, your JS would now use those, like so:
$(document).ready(function() {
$.getJSON('../../../js/statesCities.json', function(data) {
var items = [];
var options = '<option value="">Selecione</option>';
$.each(data, function(key, val) {
options += '<option value="' + val.sigla + '">' + val.sigla + '</option>';
});
// always cache your jquery dom lookups in a var if queries more than once.
var $estados = $("#estados");
var $cidades = $("#cidades");
$estados.html(options);
$estados.change(function() {
var options_cidades = '<option value="">Selecione</option>';
var str = "";
$("option:selected", $estados).each(function() {
str += $(this).text();
});
$.each(data, function(key, val) {
if (val.sigla == str) {
$.each(val.cidades, function(key_city, val_city) {
options_cidades += '<option value="' + val_city + '">' + val_city + '</option>';
});
}
});
$cidades.html(options_cidades);
$cidades.val($cidades.attr("initial-val"));
}).change();
// now set the value on the "estados" <select> and trigger the change event, so the above code runs to change "cidades"
$estados.val($estados.attr("initial-val")).trigger( "change" );
});
});});
That, I hope gets you a solution you can build upon.

Related

On remove select2 option trigger ajax remove from mysql

i am trying to build an crud operation with php and js(ajax) and i have some filters which user can add more filters to a category works fine on adding operation, but on edit i did with ajax and on click is retriving from databse and fill the inputs but on select2 i retrive data like this:
var main_id = $(this).attr("id");
$.ajax({
url:"<?php echo $site_url;?>/actions/get_filters.php",
method:"POST",
data:{main_id:main_id},
dataType:"json",
success:function(data){
var fl = [];
var nr = [];
$.each(data, function(i, field){
fl.push(field.fil_opt+","+field.txt_fil);
nr.push(field.id);
});
for (i = 0; i < nr.length; ++i) {
$('#filters_cat_update > option').each(function() {
$(this).attr('data-id', nr[i++]);
});
}
$('#filters_cat_update').val(fl);
$('#filters_cat_update').trigger('change'); // Notify any JS components that the value changed
}
});
I detect when i remove an option like this:
//remove from edit options
$('#filters_cat_update').on('select2:unselecting', function (e) {
console.log(e.params.args.data.id);
});
My html looks like this:
<div class="col-lg-6 col-md-12 col-sm-12">
<select class="js-example-basic-multiple custom-select mr-sm-2" name="filters_update[]" multiple="multiple" id="filters_cat_update">
<?php
$sqlf = mysqli_query($conn, "SELECT * FROM filtre WHERE vizibil=1 ORDER BY pozitie");
while ($rf = mysqli_fetch_assoc($sqlf)) {?>
<option data-id="" value="<?=$rf['id'];?>,<?=$rf['nume'];?>"><?=$rf['nume'];?></option>
<?php } ?>
</select>
</div>
What i want to do is when i click one option for example "color" to go with ajax and delete from table mysql where i have filters saved for each category and remove it.
As you see in my option i have concatenaded id of filter and name of filter coming from another table where user can create filters.
Thank you in advance.
You can get data-id using $("#filters_cat_update option:selected") which will give you selected option using this you can use .attr and .val() to get required values .
Demo Code :
$('#filters_cat_update').select2();
$('#filters_cat_update').on('select2:unselecting', function(e) {
var code = $("#filters_cat_update option:selected").attr('data-id'); //getting id
var values = $("#filters_cat_update option:selected").val(); //get values
var datas = values.split(',');
var id = datas[0]; //id
var color = datas[1]; //color
console.log("id - " + id + " color - " + color + " data-id -" + code)
//ajax call
$.ajax({
url: "your url",
method: "POST",
data: {
id: id,
color: color,
code :code
}, //send data
success: function(data) {
console.log("done")
}
});
});
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-beta.1/dist/js/select2.min.js"></script>
<select class="js-example-basic-multiple custom-select mr-sm-2" name="filters_update[]" multiple="multiple" id="filters_cat_update">
<option data-id="2" value="1,Color">Color</option>
<option data-id="7" value="2,Color2">Color2</option>
<option data-id="77" value="3,Color3">Color3</option>
</select>

Codeigniter 3 ajax calculating from another input using jquery

So the idea is to manipulate the value that is delivered by Ajax. This value should be divided by 20 and the result should be multiplied by the value from #nilai_hari input.
Here's my code
// trigger
<select class="form-control" id="id_anggota" name="id_anggota">
<option>-Pilih Karyawan</option>
<?php $no=1; foreach ($listAnggota as $l) {?>
<option value="<?php echo $l->id_anggota; ?>">
<?php echo $l->nama_lengkap; ?>
</option>
<?php $no++; }?>
</select>
// the effected
<select class="tunjangan_makan form-control total_tunjangan nominal" id="tunjangan_makan" name="tunjangan_makan"></select>
// another trigger
<input type="text" id="nilai_hari" name="nilai_hari" class="form-control">
And here's the script
$('#id_anggota').change(function() {
var id = $(this).val();
$.ajax({
url: "<?php echo base_url();?>hrd/penggajian/get_subpenggajian",
method: "POST",
data: {
id: id
},
async: false,
dataType: 'json',
success: function(data) {
var html = '';
var i;
for (i = 0; i < data.length; i++) {
if (data[i].flat_tunjangan == 1) {
html += '<option value="' + data[i].tunjangan_makan + '">' + number_format(data[i].tunjangan_makan, 0, '', '.') + '</option>';
} else {
$('#tunjangan_makan', '#nilai_hari').keyup(function() {
var nilai_hari = $("#nilai_hari").val(),
makan = ((data[i].tunjangan_makan / 20) * nilai_hari)
html += '<option value="' + makan + '">' + number_format(makan, 0, '', '.') + '</option>';
})
}
}
$('.tunjangan_makan').html(html);
}
});
});
So, the value of the data in which flat_tunjangan is 0 must be calculated from another input. Thanks in advance
You are doing it wrong. You should call other input onkey event and call same ajax request again and remove that onkey event inside $('#id_anggota').change().
$('#id_anggota').change(function(){
var id=$(this).val();
// perform ajax and get data
var data = [{'flat_tunjangan': '1', 'tunjangan_makan': '20'}, {'flat_tunjangan': '0', 'tunjangan_makan': '30'}];
var html = '';
var i;
for(i=0; i<data.length; i++){
if(data[i].flat_tunjangan == 1){
html += '<option value="'+data[i].tunjangan_makan+'">'+data[i].tunjangan_makan+'</option>';
} else {
var nilai_hari = $("#nilai_hari").val(),
makan = ((data[i].tunjangan_makan/20)*nilai_hari)
if (makan != '') {
html += '<option value="'+makan+'">'+makan+'</option>';
}
}
}
$('.tunjangan_makan').html(html);
});
$("#nilai_hari").keyup(function(){
var nilai_hari = $(this).val();
// again do ajax reqeust and fetch data using selected tunjangan_makan id
var id = $('#id_anggota').val();
var data = [{'flat_tunjangan': '1', 'tunjangan_makan': '20'}, {'flat_tunjangan': '0', 'tunjangan_makan': '30'}];
var html = '';
var i;
for(i=0; i<data.length; i++){
if(data[i].flat_tunjangan == 1){
html += '<option value="'+data[i].tunjangan_makan+'">'+data[i].tunjangan_makan+'</option>';
} else {
var nilai_hari = $("#nilai_hari").val(),
makan = ((data[i].tunjangan_makan/20)*nilai_hari)
if (makan != '') {
html += '<option value="'+makan+'">'+makan+'</option>';
}
}
}
$('.tunjangan_makan').html(html);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control" id="id_anggota" name="id_anggota">
<option value="1">Test 1</option>
<option value="2">Test 2</option>
</select>
<select class="tunjangan_makan form-control total_tunjangan nominal" id="tunjangan_makan" name="tunjangan_makan"></select>
<input type="text" id="nilai_hari" name="nilai_hari" class="form-control">

Jquery not gathering textarea values and not sending arrays to php under specific conditions

I am trying to make a system that gets the value of all textareas into one array and then send it to php for processing, if a page only has textareas with textbox like here:
<div class='form-group'>
<textarea class='col-sm-2' id='" + counter + "'></textarea>
<div class='col-sm-10'>
<input type='text' class='form-control'></input>
</div>
</div>
Everything goes fine. However if the page includes radio boxes:
<div class='form-group'>
<textarea class='col-sm-2' id='" + counter + "'></textarea>
<div class='radio'>
<input type='radio' name='optradio'></input>
<textarea class='col-sm-2' id='" + counter + "'></textarea>
</div>
<div class='radio'>
<input type='radio' name='optradio'></input>
<textarea id='" + counter + "'></textarea>
</div>
</div>
The jquery code does not collect all textareas and does not successfully send it to the php code for processing.
$("#save").click(function () {
for (var i = 0; i < counter; i++) {
form1[i].push($("#" + i).val());
}
$.post("FormResponse.php", {form: form1, formid:$("#formnum").val()}, function (response, status) {
document.write(response);
});
Update:
I changed my jquery code around to get both the type and the textarea values in one place and it still doesn't work. I didn't want to use objects because I want it to be easy for my php code to differentiate which textareas belong to which inputs.
Here is the code revision:
$("#save").click(function () {
var ind = 0;
for (var i = 0; i < inputcounter; i++) {
if (document.getElementById("input#" + i) !== null) {
form1.push($("input#" + i).type());
ind = ind + 1;
}
form1[ind].push($("textarea#" + i).val());
}
document.write(form1);
$.post("FormResponse.php", {form: form1, formid: $("#formnum").val()}, function (response, status) {
document.write(response);
});
});
Haven't tested it but try this.
$("#save").click(function () {
var data = {};
$.each($('textarea'),function(){
var $this = $(this);
data[$this.id] = $this.val();
})
$.post("FormResponse.php",data,function(rep){
console.log(rep);
});
});
Edit
I have no idea what your comment means.
You do realize that you sending a object in your code right?
The PHP code still accesses the data in the same way.
If you mean that you don't know what index the data will be in, then try the code below.
$("#save").click(function () {
var data = {};
$.each($('textarea'),function(){
var $this = $(this);
data[$this.id] = $this.val();
})
$.post("FormResponse.php",{form:data, formid:$("#formnum").val()},function(rep){
console.log(rep);
});
});

nested selectbox - set second jquery dropdown when first is changed

I am trying to create a dynamic set of dropdown boxes, using jQuery/AJAX and PHP/MySQL. The first dropdown box will be populated when the page loads based on values from a database. The second dropdown box should display a set of values based on the selection from the first dropdown box.
I used Chosen plugin in order to have search option.
My problem is: when I select the first selectbox, nothing is shown in the second selectbox. when I remove class="chosen-select"from the Html, it works correctly!
I need the search in selectbox. So, what should I do?
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('.chosen-select').chosen({
no_results_text: "Oops, nothing found!"
});
$('#search1').on('change', function (){
$('#search2').html("<option value=''>Select</option>");// add this on each call then add the options when data receives from the request
$.getJSON('select.php', {id: $(this).val()}, function(data){
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['Date'] + '</option>';
}
$('#search2').html(options);
//$('.chosen-select').chosen();
});
});
});
</script>
This is the second select:
<select id="search2" name="search" type="text" data-placeholder="Choose an Option..." style="width:370px;" class="chosen-select" onChange="drawChart(this.value);">
<option value=""></option>
</select>
Thank you in Advance.
Finally, I found the answer :)
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('.chosen-select').chosen({
no_results_text: "Oops, nothing found!"
});
$('select#search1').on('change', function (){
$('select#search2').html("<option value=''>Select the Option..</option>");// add this on each call then add the options when data receives from the request
$.getJSON('select.php', {id: $(this).val()}, function(data){
$('select#search2').empty();
var options = '<option value="0">Select the Option..</option>';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x]['id'] + '">' + data[x]['Date'] + '</option>';
}
$('select#search2').chosen();
$('select#search2').html(options);
$("#search2").trigger("chosen:updated");
});
});
});
</script>

Jquery populate selection list

I'm using Jquery and Ajax function to get data from MySql and put it in a div where can I select them.
It works like this:
When I select a country from the list Jquery runs a function to display a list of cities in selected country using getJson. That list is displayed in "inputString" div.
Now I want to show the same data in a html select form, not in a DIV as it is right now.
The HTML looks like:
<select name="country" id="country" class="country">
<option value="USA">USA</option>
<option value="UK">UK</option>
<option value="serbia">Serbia</option>
</select>
<input size="30" id="inputString" type="text" name="inputString" class="inp"/>
<div class="suggestionList" id="autoSuggestionsList"></div>
Jquery:
$(document).ready(function () {
$("#inputString").keyup(function () { // inputString is DIV where list of cities are listed
var up_country = $("#country option:selected").val();
$.getJSON("cities.php?queryString=" + up_country + "", function (data) {
if (data.length > 0) {
$.each(data, function (i, data) {
var city = data.city;
if (i < 19) {
$('#autoSuggestionsList').append('<li class="k' + i + '">' + city + '</li>');
}
});
}
});
});
});
How can I display the list of cities of the selected country in html select form like this one below if the select country was UK?
<select name="city" id="city" class="city">
<option value='London'>London</option>
<option value='Manchester'>Manchester</option>
<option value='Salford'>Salford</option>
</select>
$('#country').after('<select name="city" id="city" class="city"/>');
$.each(data, function(index, datum){
$('#city').append($('<option/>').val(datum).text(datum));
});
try something like that-
in your html:
<select name="city" id="city" ></select>
and your jQuery code:
$.each(data, function(i, data){
var city = data.city;
if(i < 19){
$('#city').append('<option>'+ city+ '</option>');
}
}
<select class="suggestionList" id="autoSuggestionsList"></select>
<script>
$.getJSON("cities.php?queryString=" + up_country +"", function(data) {
var content = '';
$.each(data, function(){
content += '<option value="' + this.city + '">' + this.city + '</option>';
});
$('#autoSuggestionsList').html(content);
});
</script>
The response from php can be a form or any other html content. You can load html from php if you don't necessarily need to populate the list with jquery
--for example--
response from php
echo '<form>
<select>
<option>London</option>
<option>Manchester</option>
<option>Salford</option>
</select>
</form>
';
ajax loaded content
$('#citiesList').html(data);

Categories