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?
Related
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've a select element on a form and I need that when I click on it that some code executes AND when I choose an option that no code is executed.
The code below is being executed twice so I cannot choose an option, the code executes itself again and I'm left with a reset on the option I choose.
The HTML:
<select class="form-control" id="opportunity_id" name="opportunity_id">
<option value="">(Choose opportunity)</option>
</select>
The JS:
$('#opportunity_id').on('click', function(ev) {
$.ajax({
url: "/opportunitylist/",
type: 'GET',
success: function(resOpportunities) {
var $select = $('#opportunity_id');
$select.find('option').remove();
var count = 0;
$select.append("<option value=''>(Choose opportunity)</option>");
$.each(eval(resOpportunities), function(key, value) {
$select.append('<option value=' + value[0] + '>' + value[1] + '</option>');
count = count+1;
});
}
});
});
My question, there is some fix to this code? How can I get this code executed once each time I click on the select element?
Solved with on focus
$('#opportunity_id').on('focus', function(ev) {
$.ajax({
url: "/opportunitylist/",
type: 'GET',
success: function(resOpportunities) {
var $select = $('#opportunity_id');
$select.find('option').remove();
var count = 0;
$select.append("<option value=''>(Choose opportunity)</option>");
$.each(eval(resOpportunities), function(key, value) {
$select.append('<option value=' + value[0] + '>' + value[1] + '</option>');
count = count+1;
});
}
});
});
You can try removing the event handler whenever the event gets triggered using event chaining like :
$('.selector')
.off('click', '.item')
.on('click', '.item', function() {
// code goes here
})
So in your case it will be like :
$('#opportunity_id').off('click').on('click',callBackEnd());
function callBackEnd(ev) {
$.ajax({
url: "/opportunitylist/",
type: 'GET',
success: function(resOpportunities) {
var $select = $('#opportunity_id');
$select.find('option').remove();
var count = 0;
$select.append("<option value=''>(Choose opportunity)</option>");
$.each(eval(resOpportunities), function(key, value) {
$select.append('<option value=' + value[0] + '>' + value[1] + '</option>');
count = count+1;
});
}
});
}
With this code i get the first 2 results of my JSON array. How can I "load more" by scrolling?
function suchen() {
var suche = document.getElementById("mysearch").value;
$.ajax({
url: 'http://XXX.de/?apikey=XXX&search=' + suche + '&callback=?',
type: "GET",
dataType: 'json',
success: function daten (response) {
$( 'ul#suche li' ).remove();
var i = 0;
response.forEach(function(data) {
if(i >= 2)
return false;
$('ul#suche').append('<li class="item-content"><div class="item-inner"><div class="item-title">' + data.title + '</div></div></li>');
i++;
})
}
});
}
How can load the next (3 - 4 for example) items by scrolling?
Before that, I'd mention that if you use id in selector you don't need to specify node type.
I mean use $('#suche') instead of $('ul#suche')
When it comes to infinite scroll, you should definitely specify items amount in your ajax call to get a exact chunk you need. Maybe to specify from and amount if your API gives a possibility.
Like this:
var from = 0
var amount = 2
var callApi = function (from, amount) {
$.ajax({
url: 'http://XXX.de/?apikey=XXX&search=' + suche + '&from' + from + '&amount=' + amount + '&callback=?',
success: function (response) {
response.forEach(function(data) {
$('#suche').append(
'<li class="item-content">' +
'<div class="item-inner">' +
'<div class="item-title">' + data.title + '</div>' +
'</div>' +
'</li>'
);
});
// increase from on each call
from += amount;
}
});
};
// call it
callApi(from, amount);
Then you need to add scroll eventListener and when last element appears on window canvas, call it again.
var lastChild, lastChildPosition, bottomPosition, bottomPosition
$(document).on('scroll', function (e) {
lastChild = $('#suche li:last-child');
lastChildPosition = lastChild.scrollTop();
scrollTop = $(this).scrollTop();
bottomPosition = scrollTop + $(window).height();
// call it again
if (bottomPosition > lastChildPosition) {
callApi(from, amount);
}
})
Thank you very much. I try to build a version with Wordpress which is based on your idea:
function suchen_api(lastindex) {
var suche = document.getElementById("mysearch").value;
var offset = lastindex;
var showposts = 2;
$.ajax({
url: 'http://XXX.de/?apikey=XXX&search=' + suche + '&offset=' + offset + ' &showposts=' + showposts + '&callback=?',
type: "GET",
dataType: 'json',
success: function(response){
response.forEach(function(data) {
$('ul#suche').append('<li class="item-content"><div class="item-inner"><div class="item-title">' + data.title + '</div></div></li>');
myApp.hideIndicator(); // Preloader geht aus
$$('.infinite-scroll-preloader').remove();
})
}
});
}
function suchen() {
$( '#suche li' ).remove();
var startindex = 0;
suchen_api(startindex);
}
// on Scroll
$$('.infinite-scroll').on('infinite', function () {
var startindex = $("ul#suche li").length;
suchen_api(startindex);
})
There is only one problem. Sometimes it shows me the last one doubled. Do you have an idea?
can we write two ajax success function on same page because sometimes its work sometime not
doajaxpost function is to load data in 2nd dropdown list when 1st dropdown list onchange function call by using ajax
and searching function is to load data in table by using ajax
but it sometime get execute properly sometimes not showing any result
function doAjaxPost(instituteId) {
alert(instituteId);
// get the form values
/* var name = $('#name').val();
var education = $('#education').val(); */
$.ajax({
type : "POST",
url : "/paymentGateway/merchant",
dataType : "json",
data : "institutionId=" + instituteId,
success : function(data) {
// we have the response
alert(data + "hiee");
var $merchantId = $('#merchant');
$merchantId.find('option').remove();
$("#merchant").append("<option value='ALL'>ALL</option>");
$.each(data, function(key, value) {
$('<option>').val(value.merchantId).text(value.merchantId)
.appendTo($merchantId);
});
},
error : function(e) {
alert('Error: ' + e);
}
});
}
function searching() {
// get the form values
var institutionId = $('#instiuteId').val();
var merchantId = $('#merchant').val();
var userType = $('#userType').val();
var userStatus = $('#userStatus').val();
var userId = $('#userId').val();
alert("insti=" + institutionId + "mecrhant=" + merchantId + "usertyep="
+ userType + "users=" + userStatus + "userid=" + userId);
$.ajax({
type : "POST",
url : "/paymentGateway/searching",
dataType : "json",
data : {
institutionId : institutionId,
merchantId : merchantId,
userId : userId,
userStatus : userStatus,
userType : userType
},
success : function(data) {
// we have the response
alert(data);
/* var $merchantId = $('#dynamictable');
$merchantId.find('table').remove();
$('#dynamictable').append('<table></table>');
var table = $('#dynamictable').children(); */
$("#tablenew tbody tr:has(td)").remove();
$.each(data, function(key, value) {
/* alert(value.institutionId); */
$('#tablenew tbody:last').append(
"<tr><td>" + value.userId + "</td><td>"
+ value.firstName + "</td><td>"
+ value.userStatus + "</td><td>"
+ value.userType + "</td><td>"
+ value.userAddedBy + "</td><td>"
+ value.userRegisteredDateTime
+ "</td><td>" + value.recordLastUpdatedBy
+ "</td><td>" + value.recordLastUpdatedTime
+ "</td></tr>");
});
},
error : function(e) {
alert('Error: ' + e);
}
});
}
It could be a caching issue, try to setup
$.ajaxSetup({ cache: false });
See
How to prevent a jQuery Ajax request from caching in Internet Explorer?
I got the same problem. You'll have to use the class instead of ID to make it work. Use $(".merchant") to replace $("#merchant"), and update 'merchant' to be a class.
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.