select isn't populating from JSON data - javascript

I'm having trouble with the following code.
The JSON data seems to be generated properly and the select field is being emptied of existing options as I expect it should, however, the options generated from the JSON data are not being appended to the select.
I'm not getting a console error and I am not seeing what why it's not appending.
Any suggestions?
<script>
$('#campReg').change(function() {
var $self = $(this);
$.ajax ({
url: 'php/getCamps.php',
data: { id : $self.val()},
dataType:'JSON',
type:'POST',
success: function(data){
var sel = $('#otherCamps').empty();
var toAppend = '';
$.each(data,function(i,data){
toAppend += '<option value="'+data.id+'">'+data.desc+'</option>';
});
$('#sessions').append(toAppend);
}
})
});
</script>
The JSON:
{data: [{id:1, desc:06/09 - 06/13 - WEATHER}, {id:3, desc:08/01 - 08/04 - TEST CAMP}]}

Here is the Working Fiddle:
Make these two changes to your code:
$.each(data.data,function(i,data){
and
$('#otherCamps').append(toAppend);
So your code will be:
$('#campReg').change(function() {
var $self = $(this);
$.ajax ({
url: 'php/getCamps.php',
data: { id : $self.val()},
dataType:'JSON',
type:'POST',
success: function(data){
$('#otherCamps').empty();
var toAppend = '';
$.each(data.data,function(i,data){
toAppend += '<option value="'+data.id+'">'+data.desc+'</option>';
});
$('#otherCamps').append(toAppend);
}
})
});

I think success: function(data) receives the whole json object in data, but it has a data property that holds the actual array. So you have to iterate over data.data: $.each(data.data, ...

Based on your comment, you need to use:
$('#otherCamps').append(toAppend);
instead of:
$('#sessions').append(toAppend);
since you've assigned id="otherCamps" to your select element.

Related

Only add data to ajax call if it isnt a null value

I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks
You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});

How to get JSON data into option list

I am getting JSON in the following format (as array of objects)
[{"0":"Ahmednagar","city_name":"Ahmednagar","1":"1","city_id":"1"},{"0":"Akola","city_name":"Akola","1":"2","city_id":"2"},{"0":"Amravati","city_name":"Amravati","1":"3","city_id":"3"},{"0":"Aurangabad","city_name":"Aurangabad","1":"4","city_id":"4"},{"0":"Beed","city_name":"Beed","1":"5","city_id":"5"},{"0":"Bhandara","city_name":"Bhandara","1":"6","city_id":"6"},{"0":"Buldhana","city_name":"Buldhana","1":"7","city_id":"7"},{"0":"Chandrapur","city_name":"Chandrapur","1":"8","city_id":"8"},{"0":"Dhule","city_name":"Dhule","1":"9","city_id":"9"},{"0":"Gadchiroli","city_name":"Gadchiroli","1":"10","city_id":"10"},{"0":"Gondia","city_name":"Gondia","1":"11","city_id":"11"},{"0":"Hingoli","city_name":"Hingoli","1":"12","city_id":"12"},{"0":"Jalgaon","city_name":"Jalgaon","1":"13","city_id":"13"},{"0":"Jalna","city_name":"Jalna","1":"14","city_id":"14"},{"0":"Kolhapur","city_name":"Kolhapur","1":"15","city_id":"15"},{"0":"Latur","city_name":"Latur","1":"16","city_id":"16"},{"0":"Mumbai City","city_name":"Mumbai City","1":"17","city_id":"17"},{"0":"Mumbai Suburban","city_name":"Mumbai Suburban","1":"18","city_id":"18"},{"0":"Nagpur","city_name":"Nagpur","1":"19","city_id":"19"},{"0":"Nanded","city_name":"Nanded","1":"20","city_id":"20"},{"0":"Nandurbar","city_name":"Nandurbar","1":"21","city_id":"21"},{"0":"Nashik","city_name":"Nashik","1":"22","city_id":"22"},{"0":"Osmanabad","city_name":"Osmanabad","1":"23","city_id":"23"},{"0":"Palghar","city_name":"Palghar","1":"36","city_id":"36"},{"0":"Parbhani","city_name":"Parbhani","1":"24","city_id":"24"},{"0":"Pune & Pimpri-Chinchwad ","city_name":"Pune & Pimpri-Chinchwad ","1":"25","city_id":"25"},{"0":"Raigad","city_name":"Raigad","1":"26","city_id":"26"},{"0":"Ratnagiri","city_name":"Ratnagiri","1":"27","city_id":"27"},{"0":"Sangli","city_name":"Sangli","1":"28","city_id":"28"},{"0":"Satara","city_name":"Satara","1":"29","city_id":"29"},{"0":"Sindhudurg","city_name":"Sindhudurg","1":"30","city_id":"30"},{"0":"Solapur","city_name":"Solapur","1":"31","city_id":"31"},{"0":"Thane","city_name":"Thane","1":"32","city_id":"32"},{"0":"Wardha","city_name":"Wardha","1":"33","city_id":"33"},{"0":"Washim","city_name":"Washim","1":"34","city_id":"34"},{"0":"Yavatmal\t","city_name":"Yavatmal\t","1":"35","city_id":"35"}]
ajax call to get json
$(document).ready(function(){
$("#select_state").change(function() {
var $state_var=$('#select_state').val();
alert("Selected State Value "+$state_var);
//make the ajax call
$.ajax({
url: 'ajax/location.php',
type:'GET',
data: {
state_name : $state_var
},
success: function(city_list) {
console.log(city_list);
var options = '';
for (var i = 0; i < city_list.length; i++) {
var city = city_list[i];
options += '<option value="' + city.city_id + '">' + city.city_name + '</option>';
}
$('#select_city').html(options);
$('#select_city').show();
}
});
});
});
Now it gives me only undefined is option list
You need to add:-
dataType;'json',
In your $.ajax code so that your response is automatically parsed and success function will execute properly.
Like below:-
$.ajax({
url: 'ajax/location.php',
type:'GET',
dataType:'json', // add this
data: {
state_name : $state_var
},.....rest code

Append ajax result to a select 2 multiple

i need to append to a select2 multiple, some results fetched from ajax. I try to achieve this result using this code:
<select name='prodotti' rows='5' multiple id='prodotti' class='select2'></select>
Here is JS
$('#close-modal').on('click', function (e) {
var id = $('#id').val();
$.ajax({
type: 'GET',
url: '/items-fattura?id=' + id,
success: function (response) {
$("#prodotti").val(response);
}
});
});
Ajax return this results:
[{"id":2,"nome":"Certificato SSL POSITIVE"}]
Can someone help me to resolve?
Use $.each to iterate through your JSON array that you receive from ajax call.
Note:- the spelling of success, you have written sucess.
success: function(data){
data = JSON.parse(data);
var toAppend = '';
$('#prodotti').empty();
$.each(data, function(i,o){
toAppend += '<option value="'+ o.nome +'">'+o.id+'</option>';
});
$('#prodotti').append(toAppend);
}
You can try this.
$.ajax({
type: 'GET',
url: '/items-fattura?id=' + id,
success: function (response) {
var $el = $("#prodotti");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", 0)
.text('Select'));
for (i = 0; i < response.length; i++) {
$el.append($("<option></option>")
.attr("value", response[i]['id'])
.text(response[i]['name']));
}
}
});
If you receiving multiple values that are separated by comma, you can use this select2 trick to set the values:
var makeArray = commanSeparatedValues.split(',');
$('#SELECT_ID').val(makeArray);
It's an nifty little cool trick that you should use when working with select2. Avoiding the loops and $.each. Hope this helps!
take a look at
https://select2.org/programmatic-control/add-select-clear-items
for adding options to a select2 by js

How to append the values in table using AJAX

Here i am passing javascript varaible into PHP function using AJAX ,here it will be working fine,** console.log(fname);** Here i got all values but append the tables means i am getting [object Object],how can solve this error
<script type="text/javascript">
$(document).ready(function(){
$("#reservation").on("change", function() {
var reservation = $(this).val();
$.ajax({
type: 'post',
url: 'date-range.php',
data: {
logindate: reservation,
},
success: function( data ) {
var res=jQuery.parseJSON(data);// convert the json
console.log(res);
if(res['status']=="success"){
var htmlString='';
$.each( res['data'], function( key, value ) {
htmlString+='<tr>';
var ssm_id = value.ssm_id; // here i got ssmid
htmlString+='<td>'+value.ssm_id+'</td>';
htmlString+='<td>'+ $.ajax({
type: 'post',
url: 'config/functions.php',
data: {
ssm_id: ssm_id,
},
success: function( fname ) {
console.log(fname);//HERE I GOT ALL VALUES
htmlString+='<td>'+fname+'</td>';// BUT HERE I CAN'T APPENT THE VALUES IN TABLE
}
});+'</td>';
htmlString+='<td>'+'Muthuraja'+'</td>';
htmlString+='<td>'+'20-05-2016'+'</td>';
htmlString+='<td>'+'status'+'</td>';
htmlString+='<td>'+value.source+'</td>';
htmlString+='<td>'+ "<span style='color:green'>View Profile</span>"+'</td>';
/* htmlString+='<td>'+ "<span style='color:green'>Completed</span>"+'</td>';*/
htmlString+='</tr>';
});
$('#datatable-editable > tbody').empty().append(htmlString);
}
else{
$('#datatable-editable > tbody').empty().append("<center style='height:100px;padding-top:36px;color:red;font-size:17px;'><b>No matching records found</b></center>");
}
}
});
});
});
</script>
functions.php
<?php
$ssm_id = $_POST['ssm_id'];
if(!empty($ssm_id)){
echo firstname($ssm_id);
}
function firstname($id)
{
$f="SELECT firstname FROM register WHERE matri_id='$id'";
$rr=mysql_query($f);
while($row=mysql_fetch_array($rr)) {
$firstname = $row['firstname'];
}
return $firstname;
}
?>
Without knowing the exact format of your JSON, it's hard to give a definitive answer. However, assuming you have a JSON array of objects that represent your rows, you'd need to iterate over that array and for each object do the following:
Create a new <tr> element - var $tr = $('<tr/>');
For each item of information (I assume one item per <td>), create a <td> element and set its content - var $td = $('<td/>').html(x.y) (x is your current object, y is a field in the object) then append it to the row - $tr.append($td);.
Append the row before the last row in the existing table - $('.list-order tr:last').before($tr);
Following from the additional information provided in the question, the following code should do what you need to do:
success: function(result) {
//result is json format
var $tr = $('<tr/>');
$tr.append($('<td/>').html(result.itemname));
$tr.append($('<td/>').html(result.qty));
$tr.append($('<td/>').html(result.prices));
$('.list-order tr:last').before($tr);
}

Generate multiple HTML elements from JSON using Jquery?

How to use Jquery and Javascript to extract JSON from $ajax and then do a foreach, and create a string that will append to html DOM?
Something like:
$(document).ready(function (e) {
$.ajax({
type: "POST",
url: "Companies/GetSearchRatios",
context: this,
success: function (data) {
//return JSON
}
});
Result JSON
[{"name":"MyNAme","value":350},{"name":"Hello","value":356}]
I can easily acces this values inside $ ajax method success, but how can I extract this value outside of method and use it to append to DOM?
This is what I need as a result of some for/foreach method:
var $gElemRatios =
'<option value=""></option>' +
'<option value="350">MyNAme</option>' +
'<option value="356">Hello</option>';
Then I use this var to combine with another:
var $gElem =
'<div class="cbox cboxQuarterWidth">' +
'<select id="combobox_0">' +
$gElemRatios + // here I add previous generated elem
'</select>' +
'</div>';
And finally:
$("#main").append($gElem);
Any ideas?
You can use $.each to loop through the data passed to the success handler:
$.ajax({
type: "POST",
url: "Companies/GetSearchRatios",
context: this,
success: function (data) {
$.each(data,function(){
console.log(this.name); //just an example how to access things
$('#select').text(this.value); //maybe?
});
}
});
See this fiddle

Categories