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
Related
We want to bind json response to li elements with each element having value as id and text as name.
$.ajax({
type: "GET",
url: "/api/xyz/",
dataType: "json",
success: function(response) {
var items = [];
$.each(response, function(i, item) {
items.push('<li</li>",{value:item.id,text:item.name}');
});
$('#formFieldCity ul').append(items.join(''));
}
});
But no success, I don't see any binding. Can anyone help?
you should write like this:
$.each(data, function(i, item) {
items.push('<li id="'+item.id+'">'+item.name+'</li>');
});
I think you mean
var list = $('#formFieldCity ul'); //caching
$.ajax({
type: "GET",
url: "/api/xyz/",
dataType: "json",
success: function (response) {
var items = [];
//Misplaced variable here: data instead of response
$.each(response, function(i, item) {
var mapped = {value:item.id,text:item.name};
items.push(mapped)
list.append("<li id=\""+item.id+"\">"+item.name+"</li>");
});
}
});
This will basically print a json in your HTML.
Hope I got what you wanted.
EDIT:
If your response is an array, consider using a simple for loop, which is about 8x faster then the jQuery.each
for(var i=0; i<response.length; i++){
var mapped = {value:response[i].id,text:response[i].name};
items.push(mapped)
list.append("<li id=\""+mapped.value+"\">"+mapped.text+"</li>");
}
I hope I can explain my issue clearly.
I am running a function to get values from a database using ajax, and adding each result as a row in a table. This is so the user can delete or edit any row they want. I'm adding IDs dynamically to the columns and also the edit and delete buttons which are generated. So it looks like this:
My code:
function getstationdata(){
var taildata1 = $('#tailnumber2').val();
var uid = $('#uid').val();
$.ajax({
// give your form the method POST
type: "POST",
// give your action attribute the value ajaxadd.php
url: "ajaxgetstationdata.php",
data: {tailnumber:taildata1, uid:uid},
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
var trHTML = '';
$.each(response.result, function( index, value) {
trHTML += '<tr><td><input type="text" value="' + value[2] + '"></td><td><input type="text" class="weightinputclass"value="' + value[3] + '"></td><td><input type="text" class="arminputclass"value="' + value[4] + '"></td><td><input type="text" class="momentinputclass" value="' + value[5] + '"></td><td><button id="updatecgbtn" onclick="updatecg()"class="editbuttonclass">Edit</button></td><td><button id="deletecgbtn" class="deletebuttonclass"">Delete</button></td></tr>';
});
$('#mbtbody').html('');
$('#mbtbody').html(trHTML);
var ID = 0;
$('.weightinputclass').each(function() {
ID++;
$(this).attr('id', 'weightinputboxID'+ID);
});
var ID = 0;
$('.arminputclass').each(function() {
ID++;
$(this).attr('id', 'arminputboxID'+ID);
});
var ID = 0;
$('.momentinputclass').each(function() {
ID++;
$(this).attr('id', 'momentinputboxID'+ID);
});
var ID = 0;
$('.editbuttonclass').each(function() {
ID++;
$(this).attr('id', 'editbutton'+ID);
});
var ID = 0;
$('.deletebuttonclass').each(function() {
ID++;
$(this).attr('id', 'deletebutton'+ID);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The code I have when adding the info is in a form and it looks like this:
$('#addstations').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
chartdata4=(tailnumber3.value)
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
I searched a bit on the internet and found out that I can't add a form inside my table for each row which would have been easy to do and I can reuse my code which I use when adding new info.
So, can someone please point me in the right direction?
Here is the direction you could go
$('#formTable').on('click',"button" function(e){
var $row = $(this).closest("tr"), $form = $("#addstations");
var data = {
passenger:$row.find("passengerClass").val(),
weight :$row.find("weightClass").val()
} // no comma on the last item
data["type"]=this.className=="deletebuttonclass"?"delete":"edit";
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
dataType: 'json',
cache: false,
})
...
I assume that the problem is that you want to add a form as a child of a table / tbody element to wrap your row. You cannot do that and the browser will most likely strip the form tags, leaving you with nothing to serialize.
There are different solutions for that, for example:
Build the data object manually in javascript when a button on a row is clicked;
Use a non-form grid solution for your layout.
Add each row in its own table and have the form wrap that table
The third solution is a bit of a hack, I would use the first or the second myself.
I have a list of "User" with has Name, Surname and Email.
I need to loop through it on Jquery. This list is returned by a server side method
success: function (result) {
// var res = result.d
$.each(result, function (index, obj) {
alert(obj);
});
}
Does anyone know how it can be done?
Edit: The entire Ajax list:
var param = '{"NameofMap":"' + nofm + '", "VillNum":"' + numberV + '"}';
$.ajax({
url: 'GenerateMap.aspx/AddVill',
type: "POST",
data: param,
dataType: "json",
contentType: "application/json",
error: function (msg)
{ alert("Fails"); },
success: function (result) {
$.each(result, function (index) {
alert("Test");
});
}
});
This is the entire Ajax. It returns a list of Class instances ("User")
It displays "Test" but if I change that with alert(result[index].Name); , it displays just an empty box.
As you haven't provide proper information, still you can give this a try.
If you're getting into the success: and able to get alert, you can try like this:
You can have properties with it's name
--> result.Name
--> result.Surname
--> result.email
So Your code will be like following:
$.each(result, function(index) {
alert(result[index].Name);
.......
});
Or
$.each(result, function(index, item) {
alert(item.Name);
.......
});
This might help!
try
$.each(data,function(i, item){
alert(item.name)
});
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.
So I came up with this script that ajax calls google's suggestions and JSONP returns the search results. I managed to make the results sorted but I'd like to implement jquery autocomplete instead. I've tried any possible way I could think of but haven't got any results.
Here is the a working fiddle: http://jsfiddle.net/YBf5J/
and here is the script:
$(document).ready(function() {
$('#q').keyup(retrieve);
$('#q').focus();
$('#results').show('slow');
$("#q").autocomplete(parse, {
Height:100,
width:620,
noCache: false,
selectFirst: false
});
});
function retrieve() {
$.ajax({
type: "GET",
url: 'http://suggestqueries.google.com/complete/search?qu=' + encodeURIComponent($('#q').val()),
dataType: "jsonp",
jsonpCallback: 'parse'
});
}
var parse = function(data) {
var results = "";
for (var i = 0; i < data[1].length; i++) {
results += '<li>' + '' + data[1][i][0] + '' + '</li>';
}
$('#results').html('' + results + '');
$('#results > li a').click(function(event) {
event.preventDefault();
$('#q').val($(this).html()).closest('form').submit();
});
}
And here's the simple body:
<body><input type="text" id="q"><div id="results"></div></body>
Any help is really appreciated.
Thanks alot, rallyboy.
Here is an example of using the Jquery-UI Auto complete. Taken from your code, all i did was update the auto complete source every time the data changes using this code.
var parse = function(data) {
var results = [];
for (var i = 0; i < data[1].length; i++) {
results.push(data[1][i][0]);
}
$('#q').autocomplete({
source: results
});
See fiddle
http://jsfiddle.net/WUcpC/1/
It uses just the base CSS but that can be changed by pointing it at which ever theme you want.