I have a form that submits a new entry via ajax and returns the entry data. I'm trying to get the returned data to be automatically selected in the Select2 field. I can get the id entered as the input value, but I'm not sure how to get the text to be displayed in the span.
Here's the JS I have so far:
function clientFormatResult(client){
var markup = client.first_name + ' ' + client.last_name + ' (' + client.username + ')';
return markup;
}
function clientFormatSelection(client) {
$('#client-input').empty();
$('#client-input').append('<input type="hidden" name="client" value="' + client.id + '" />');
return client.first_name + ' ' + client.last_name + ' (' + client.username + ')';
}
$('#client-selection').select2({
placeholder: 'Select a client',
allowClear: true,
minimumInputLength: 1,
ajax: {
type: 'POST',
url: 'clients/get_client_list',
dataType: 'json',
data: function (term) {
return {filter: term};
},
results: function (data) {
return {results: data};
}
},
formatResult: clientFormatResult,
formatSelection: clientFormatSelection,
dropdownCssClass: 'bigdrop',
initSelection: function (element, callback) {
var id = element.val();
if(id != '') {
$.ajax('clients/get_client_list/'+id).done(function(data) {
data = $.parseJSON(data);
callback(data);
});
}
}
});
$('#add-client-form').submit(function(e) {
e.preventDefault();
var form = $(this),
url = form.attr('action'),
data = form.serialize();
$.post(url, data, function(data, status, xhr) {
$('.form-response').fadeOut(400);
if(status == 'success') {
$('#add-client-modal').modal('hide');
data = $.parseJSON(data);
$('#client-selection').select2('val', data.client_id);
} else {
$('#add-client-failure').fadeIn(400);
}
});
});
As you can see, the text displayed is meant to be like "John Smith (smithj)".
I sorted it out, it was an issue with the data I was returning. Select2 was expecting an id variable, but I was returning it as client_id.
Related
Hi I'm trying to figure out how to fill all fields using ajax call, it successfully doing by selecting category, it loads all related sub_categories.
But sub_sub_category fields are empty. Only when I choose sub_category option it will load all sub_sub_categories, but I want all prefilled once category has been changed. I don't mind to leave like this, but problem is if I have only single sub_category I can not select any sub_sub_category even if they have any I tried to convert to function and call them but no success.
Code below:
<script>
$(document).ready(function() {
get_sub_sub_category();
$('select[name="category_id"]').on('change', function() {
var category_id = $(this).val();
if(category_id) {
$.ajax({
url: "{{ url('/category/sub-category/') }}/"+category_id,
type: "GET",
dataType: "json",
success: function(data) {
$('select[name="sub_sub_category_id"]').html('');
var d = $('select[name="sub_category_id"]').empty();
$.each(data, function(key, value) {
$('select[name="sub_category_id"]').append('<option value="'+ value.id +'">' + value.sub_category_name + '</option>');
});
get_sub_sub_category();
},
})
} else {
alert('danger');
}
});
function get_sub_sub_category() {
$('select[name="sub_category_id"]').on('load change', function () {
var sub_category_id = $(this).val();
if (sub_category_id) {
$.ajax({
url: "{{ url('/category/sub-sub-category/') }}/"+sub_category_id,
type: "GET",
dataType: "json",
success: function (data) {
var d = $('select[name="sub_sub_category_id"]').empty();
$.each(data, function (key, value) {
$('select[name="sub_sub_category_id"]').append('<option value="' + value.id + '">' + value.sub_sub_category_name + '</option>');
});
},
})
} else {
alert('danger');
}
});
}
});
</script>
You might want to consider the following.
$(function() {
$('select[name="category_id"]').on('change', function() {
var category_id = $(this).val();
if (category_id) {
$.ajax({
url: "{{ url('/category/sub-category/') }}/" + category_id,
type: "GET",
dataType: "json",
success: function(data) {
$('select[name="sub_sub_category_id"]').html('');
var d = $('select[name="sub_category_id"]').empty();
$.each(data, function(key, value) {
$('select[name="sub_category_id"]').append('<option value="' + value.id + '">' + value.sub_category_name + '</option>');
});
$('select[name="sub_category_id"]').trigger("change");
},
})
} else {
alert('danger');
}
});
$('select[name="sub_category_id"]').on('change', function() {
var sub_category_id = $(this).val();
if (sub_category_id) {
$.ajax({
url: "{{ url('/category/sub-sub-category/') }}/" + sub_category_id,
type: "GET",
dataType: "json",
success: function(data) {
var d = $('select[name="sub_sub_category_id"]').empty();
$.each(data, function(key, value) {
$('select[name="sub_sub_category_id"]').append('<option value="' + value.id + '">' + value.sub_sub_category_name + '</option>');
});
},
})
} else {
alert('danger');
}
});
});
This defined the callbacks for both. For category, when it is changed, it triggers change event on sub-category. This in turn will cascade the loading of the next Select.
I would like once the user selects a different item in the drop box list which was taken from a mysql database, that specific data to that field be displayed.
Currently, I am able to get the value of the item in the drop down box but I am unable to use it.
<h3>Drop down Menu</h3>
<select id="dmenu">
<option selected="selected" id="opt">Choose your station</option>
</select>
<div id="optionT"></div>
$(document).ready(() => {
window.onload = ajaxCallback;
function ajaxCallback(data) {
var data;
var myOptions;
var output;
$.ajax({
url: 'http://localhost:5000/alldata',
type: 'GET',
datatype: 'json',
success: (data) => {
//$.each(data, function (index, value) {
var output = [];
$.each(data, function(key, value) {
output.push('<option value="' + key + '">' + value.Station +
'</option>');
});
$('#dmenu').html(output.join(''));
}
})
}
});
$('#dmenu').on('change', function() {
//alert( this.value );
//alert($(this).find(":selected").value());
function stationData(data) {
var stationName = $(this);
alert(stationName.val());
//var stationName = $(this).value();
//var stationName = $(this).find(":selected").value()
$.ajax({
url: 'http://localhost:5000/alldata',
method: 'POST',
data: {
station: stationName
},
success: (data) => {
$.each(data, function(i) {
data[i]
//console.log(i);
var station_loopOp = '';
//console.log(JSON.stringify(data[i].Station));
station_loopOp += '<li>ID: ' + JSON.stringify(data[i].ID) +
'</li>' +
'<li>Station: ' + JSON.stringify(data[i].Station) +
'</li>' + '<li>Address:
'+JSON.stringify(data[i].Address) +
'</li>' + '<li>' +
Sales: JSON.stringify(data[i].Monthly_CStore_Sales) +
'</li>' + '<li>Operator: ' +
JSON.stringify(data[i].Operator) + '</li>' +
'<li>Top SKU: ' + JSON.stringify(data[i].Top_SKU) +
'</li>' +
'</<li>' + '<br/>');
$('#optionT').html(station_loopOp);
}
});
}
});
You are just defining the function stationData(data){....} inside the callback function but not calling it anywhere inside of it .
Add this line into your function : stationData(<your-data>);
I have ajax in my cart page where i get destination info of the user and return shipping options to them in order to calculate their shipping cost.
So far everything works except I'm not sure how to loop returned data from my 3rd party website.
Here is what I need:
I need Loop trough this data and get marked information in drop-down.
Red: as my option group.
Orange - Green - Purple: as my option. LIKE:
OKE - 48.000 - 5-7 Days
network result
console result
Codes
This is my ajax code for that:
<script>
jQuery( document ).ready( function( $ ) {
$('body').on('change', 'select[name="city"]', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var cityID = $(this).val();
var weight = ["{{$totalWeight}}"];
if(cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/'+weight+'/'+encodeURI(cityID),
type: "GET",
dataType: "json",
success:function(data) {
// $('#des').empty();
// $('#des').append(
// '<p>Destination: ' + data['meta']['destination']['province'] + ' , ' + data['meta']['destination']['type'] + ' , ' + data['meta']['destination']['city_name'] + ' , ' + data['meta']['destination']['postal_code'] +'</p>'
// );
$.each(data.data, function(key, value) {
console.log(value);
});
}
});
}else{
$('select[name="postchoose"]').empty().append("<option value='' selected>Select</option>");
}
});
});
</script>
Thanks.
SOLVED
I retrieved my data with code below:
<script>
jQuery( document ).ready( function( $ ) {
$('body').on('change', 'select[name="city"]', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var cityID = $(this).val();
var weight = ["{{$totalWeight}}"];
if(cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/'+weight+'/'+encodeURI(cityID),
type: "GET",
dataType: "json",
success:function(data) {
$('#des').empty();
$('#des').append(
'<p>Destination: ' + data['meta']['destination']['province'] + ' , ' + data['meta']['destination']['type'] + ' , ' + data['meta']['destination']['city_name'] + ' , ' + data['meta']['destination']['postal_code'] +'</p>'
);
$.each(data.data, function(key, value) {
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
var formattedNumber = nf.format(number);
// number format
$('select[name="postchoose"]').append('<optgroup label="' + value['code'] + '" /><option id="postchoose" class="form-control" value="'+ value['code'] +'">'+ value2['service'] + ' - ' + nf.format(number) + ' Rp' + ' - ' + value3['etd'] +'</option></optgroup>');
// console.log(value);
// alert(value.code); // jne-pos
// alert(value2.service); //oke -reg
// alert(value3.value); // 43000 - etd 24 jam
});
});
});
}
});
}else{
$('select[name="postchoose"]').empty().append("<option value='' selected>Select</option>");
}
});
});
</script>
there is only 1 issue i'm facing I would like to be done and that's grouping results with <optgroup> as you see in my screenshot below my <optgroup> in looping for each one of my options.
How can I fix this?
For example, I have a class:
classA.js
$(document).ready(function() {
select2_scroll('element_name_id')
});
calling a function from
classB.js
function select2_scroll(elementId, queryString) {
resource_url: 'something/';
$('#' + elementId).select2({
allowClear: true,
ajax: {
url: resource_url,
dataType: 'json',
type: 'GET',
quietMillis: 100,
data: function (term, page) {
return {
search_term: term,
page: page
};
},
results: function (data, page) {
var more = (page * PAGE_LIMIT) < data.total_results;
return { results: data.resource, more: more };
}
},
formatResult: resourceName,
formatSelection: resourceName,
});
}
function resourceName(resource) {
var format = '<div>' + resource.name + '</div>' +
'<input type="hidden" name="' + elementId + '_id" value="' + resource.id + '"/>';
return format;
}
How do I avoid using a global variable to pass the elementId variable? I can't call resourceName directly and pass the elementId in by calling resourceName(resource, elementId).
Am I missing something from the Select2 component?
You could try something like :
formatResult: ()=>{
resourceName(resource, elementId);
},
formatSelection: ()=>{
resourceName(resource, elementId);
},
Add your element Id in your "results" return
results: function (data, page) {
var more = (page * PAGE_LIMIT) < data.total_results;
return { results: data.resource, more: more, elementId: elementId };
}
And use it in your function:
var format = '<div>' + resource.name + '</div>' +
'<input type="hidden" name="' + resource.elementId + '_id" value="' + resource.id + '"/>';
Let me know, if this works for you. I didn't have tested it with your example
I found a solution to my problem. I can just do
...
formatResult: function(resource) {
return resourceName(resource, elementId)
},
formatSelection: function(resource) {
return resourceName(resource, elementId)
},
....
Thanks!
When i click the Select working days / hours Checkbox the list of days will be displayed. for example if i click the sunday checkbox check box the value entered in the checkbox should be call to javascript function. in case am not click the checkbox the value display should be Null.
DEMO LINK HTML
$(document).ready(function () {
$("input#btnDocBusinesshours").click(function () { SaveDocBusinesshours(null) });
});
Call Ajax Function
function callAjax(jparms) {
$.ajax({
type: "POST",
url: jparms.url,
data: jparms.data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (jparms.action == "SaveDocBusinesshours")
SaveDocBusinesshours(response.d)
},
failure: function (response) { response.d; }
});
}
Save Ajax Function
function SaveDocBusinesshours(response) {
var values = $('input[type="checkbox"].single:checked').map(function () {
return $(this).val();
}).toArray();
if (response == null) {
callAjax({
url: pageUrl + '/SaveDocBusinesshours',
data: '{"Doctorid": "' + $("#<%=hdnDoctorId.ClientID %>").val() + '","WorkingDaysID" : "' + $("#<%=hdnBusiness.ClientID %>").val() + '","Sunday" : "' + $("#<%=ChkSUN.ClientID %>").val() + '","Monday" : "' + $("#<%=ChkMON.ClientID %>").val() + '","Thuesday" : "' + $("#<%=ChkTUE.ClientID %>").val() + '"}',
action: "SaveDocBusinesshours"
});
window.location.reload();
}
else {
loading(false);
if (response.AjxContactId != null) {
$('#<%=hdnBusiness.ClientID%>').val(response.AjxContactId);
}
msg(true, response.Message);
}
}
Webmethod:
[WebMethod]
public static UserAjax SaveDocBusinesshours(string Doctorid, string WorkingDaysID, string Sunday, string Monday, string Thuesday)
{
UserAjax oUserAjax = new UserAjax();
return oUserAjax;
}