javascript alert() doesn't work in IE - javascript

I have an Ajax request which in error condition alerts the message returned from server. This works in all browsers except for IE. it shows an empty alert box.
JS:
$(document).ready(function() {
$("input[name!='photo_1']").parents('.fileinput-wrapper').find(".label").remove();
$("input[type=file]").on('change',function(){
$(this).parents('label').find('.fileinput-preview').css('background',"url('http://localhost/project/assets/images/ajax-loader.GIF') no-repeat center center");
var selectedElement = this;
var name = $(this).attr('name').toString();
$('#upload').ajaxSubmit({
dataType:'json',
data: {name:name},
beforeSubmit:function(){
$(selectedElement).parents('label').find('input[type=file]').attr('disabled','disabled');
},
success: function(data) {
$(selectedElement).parents('label').find('.fileinput-preview').css('background',"url('http://localhost/project/assets/images/loading.png') no-repeat center center");
$.each(data, function(index, item) {
$("input[name=" + index + "]").parents('label').find('img').remove();
$("input[name=" + index + "]").parents('label').find('.fileinput-preview').append("<img src='http://localhost/project/uploads/" + item.NAME +"' width='190px' height='" + Math.floor(190/(item.WIDTH/item.HEIGHT)) + "px' />");
$("input[name=" + index + "]").parents('label').find('.thumbnail').css('height','');
$("input[name=" + index + "]").parents('label').find('.thumbnail').css('min-height',Math.floor(190/(item.WIDTH/item.HEIGHT)).toString()+"px");
});
$(selectedElement).parents('label').find('input[type=file]').removeAttr('disabled');
return false;
},
error : function(xhr) {
alert(xhr.responseText);
$(selectedElement).parents('label').find('.fileinput-preview').css('background',"none");
$(selectedElement).parents('label').find('.fileinput-preview').css('background',"url('http://localhost/project/assets/images/upload_a_photo.png') no-repeat center center");
return false;
}
});
});
});

Related

jQuery fresh ALL rows from PHP loop

Im not sure what is happening here, but I can not update this DIV per every row using this code. This code loads a initial user list, and loads the rest (after first 3) to a DIV dropdown triggered by click event.
<? foreach ($res as $row) { ?>
<script>
function fetchIndexUsers() {
$(function () {});
$.ajax({
url: '/ajax/ajax_live_index_users.php',
method: 'GET',
cache: false,
dataType: 'JSON',
data: {
item_id: <?=intval($row["item_id"])?>
},
success: function (data) {
var html_to_append = '';
array = [];
results = [];
$.each(data, function (i, item) {
results[i] = data[i];
array[0] = item.total;
array[1] = item.calc;
let icon = item.user.match(/(^|\W)yes($|\W)/i) ? 'arrow_upward' : 'arrow_downward';
html_to_append += '<div style="display:inline;float:left"><span class="material-icons" style="vertical-align:top;width:16px;padding-right:30px;color:#c0c0c0">' + icon + '</span></div><div style="display:inline;float:left;padding-bottom:1px"><a class="tooltip-newusers" title="' + item.username + '" href="/user/?id=' + item.user_id + '"><img style="box-shadow:2px 2px 10px #D3D3D3;height:35px;width:35px;border-radius:50%;margin-bottom:6px;margin-right:-20px;margin-top:-5px;vertical-align:middle;position:relative;z-index:10005;border:2px solid #FFF" src="/' + item.avatar + '" /></a></div><div style="clear:both"></div>';
return i <= 3;
});
if (array[0] >= 3) {
$("#live-peers-more-<?=intval($row["item_id"])?>").html('<div id="slidedown-<?=intval($row["item_id"])?>" style="user-select:none;margin-top:-14px;position:absolute;right:-20px;font-size:13px;background:purple;padding:0 6px;text-align:center;border-radius:3px;color:#FFF;font-weight:500;text-decoration:none;text-shadow:0 1px 1px rgba(0,0,0,.3);box-shadow:2px 2px 10px #D3D3D3"><a style="color:#fff;cursor:pointer">+ ' + (array.length - array[1]) + (array[1] >= 2 ? ' peers' : ' peer') + '</a></div>')
if (array[1] === 0) {
$("#live-users-more-<?=intval($row["item_id"])?>").hide();
}
}
$("#live-users-<?=intval($row["item_id"])?>").html(html_to_append);
$('.tooltip-newusers').tooltipster({
animation: 'grow',
delay: 200,
interactive: true,
theme: 'tooltipster-punk'
});
$("#live-peers-<?=intval($row["item_id"])?>").css('background', 'none');
$("#slidedown-<?=intval($row["item_id"])?>").html('<span><a style="color:#fff;cursor:pointer">+ ' + array[0] + (array[0] >= 2 ? ' peers' : ' peer') + '</a></span>');
}
});
$("#live-users-more-<?=intval($row["item_id"])?>").click(function () {
$("#slidedown-<?=intval($row["item_id"])?>").css('z-index', '9999999');
$.ajax({
url: '/ajax/ajax_live_index_users.php',
method: 'GET',
cache: false,
dataType: 'JSON',
data: {
item_id: <?=intval($row["item_id"])?>,
more: 1
},
success: function (data) {
var html_to_append = '';
$.each(results, function (i, item) {
html_to_append += '<div id="more_users" style="padding:6px;text-shadow:0 1px 1px rgba(0,0,0,.3)"><div id="peer-username">' + truncateString(item.username, 6) + '</div><a class="tooltip-newusers" title="' + item.username + '" href="/user/?id=' + item.user_id + '"><img style="height:35px;width:35px;border-radius:50%;border:2px solid #FFF" src="/' + item.avatar + '" /></a><div style="font-size:11px;font-weight:normal">' + formatBytesSpeed(item.totalspeed) + '</div></div>';
$("#slidedown-<?=intval($row["item_id"])?>").css('height', 'auto');
});
$("#slidedown-<?=intval($row["item_id"])?>").html(html_to_append);
$('.tooltip-newusers').tooltipster({
animation: 'grow',
delay: 200,
interactive: true,
theme: 'tooltipster-punk'
});
}
});
});
}
fetchIndexUsers();
setInterval(function () {
fetchIndexUsers()
}, 5000);
</script>
<div id="live-users-<?=intval($row["item_id"])?>" style="padding:10px;background:url(/images/loading-ellipsis.svg) no-repeat left">
<span style="padding-right:89px"></span>
</div>
<div id="live-users-more-<?=intval($row["item_id"])?>"></div>
<? } ?>
But any action coming back only updates the last row in from the array (PHP foreach array, with the JS emedded in the loop picking up on the ID from the iteration).
How come it only interacts with the last row? How can I update all rows since I am using a unique ID?
Thank you
You need to move the script out from the loop completely. Have ONE version of the script that delegates like this
$("#container").on("click", ".live-users-more",function () {
const item_id = $(this).prev().attr("id"); ....
and then change
<div id="live-users-more-<?=intval($row["item_id"])?>"></div>
to
<div class="live-users-more"></div>
where you have a
<div id="container"></div>
that wraps all the live user divs

Display data received from drop box value

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>);

Functions are not working in Ajax after a while

I have input which on change should send it is value to ajax and get response back. Ajax is working correct and enters to success,but does not working click function inside it if i do not do changes or click. If i click immediately after response it works, but if i do not do changes in 4-5 seconds it something like close the session. How can i avoid this timing?
here is my example of ajax
$('#unvan_search').on('keyup change', function() {
var unvan = $(this).val();
$.ajax({
type: "POST",
url: url,
data: {
'tpIdRegion': region_type_id_j + '_' + region_id_j,
'road': unvan,
'guid': my_key
},
beforeSend: function() {
console.log('before send');
},
success: function(e) {
console.log('suceess');
var output = [];
for (var i = 0; i < e.names.length; i++) {
output.push('<li class="get_street es-visible" idx="' + e.names[i].X + '" idy="' + e.names[i].Y + '" id="' + e.names[i].ID + '" value="' + e.names[i].ID + '" style="display: block;">' + e.names[i].Name + '</li>');
console.log('filled');
};
$('#unvan_select_div ul').html(output.join(''));
$("#unvan_select_div ul").on("click", '.get_street', function() {
//MY CODE HERE WHICH I CAN NOT USE AFTER 4-5 SECONDS
});
},
error: function(x, t, m) {
alert("error");
}
});
});
This binding here:
$("#unvan_select_div ul").on("click", '.get_street', function() { ... }
There’s no need to declare it in the success callback. This kind of delegate bindings is there for that purpose: being able to handle events on elements created at a later stage
It may work if you structure it like this.
var ret = false;
$.ajax({
type: "POST",
url: url,
data: {
'tpIdRegion': region_type_id_j + '_' + region_id_j,
'road': unvan,
'guid': my_key
},
beforeSend: function() {
console.log('before send');
},
success: function(e) {
ret = true;
console.log('suceess');
var output = [];
for (var i = 0; i < e.names.length; i++) {
output.push('<li class="get_street es-visible" idx="' + e.names[i].X + '" idy="' + e.names[i].Y + '" id="' + e.names[i].ID + '" value="' + e.names[i].ID + '" style="display: block;">' + e.names[i].Name + '</li>');
console.log('filled');
};
return;
},
error: function(x, t, m) {
alert("error");
}
});
});
if(ret) {
$('#unvan_select_div ul').html(output.join(''));
$("#unvan_select_div ul").on("click", '.get_street', function() {
//MY CODE HERE WHICH I CAN NOT USE AFTER 4-5 SECONDS
});
}

Retrieve data from 3rd party website by ajax in laravel

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?

Content disappears from jQuery autocomplete when focus on field is lost

my autocomplete works fine, but problem appears when I want to skip to another field in my form. When autocomplete lose focus its value disappears (also value of span that I render after this autocomplete disappears).
function initCaAutocomplete() {
$(".caSelector").autocomplete({
source: "/core/index/search-ca/ajax/1",
minLength: 2,
select: function (event, ui) {
var descId = 'desc_' + $(this).attr('id');
if ($('span#' + descId).length) {
$('span#' + descId).html(ui.item.desc);
$('span#' + descId).attr('title', ui.item.fullDesc);
} else {
$(this).after('<span title="' + (ui.item.fullDesc) + '" class="cpv_descHolder" id="' + descId + '">'
+ ui.item.fullDesc + '</span>');
}
ui.item.value = ui.item.code;
$('.tooltip', $(this).parent()).hide();
},
change: function (event, ui) {
var descId = 'desc_' + $(this).attr('id');
var inputId = $(this).attr('id');
var source = $(this).val();
$.ajax({
type : 'POST',
url : '/core/index/search-ca/ajax/1',
dataType: "text",
async : true,
data : {
term: source
},
success: function (response) {
var codes = $.parseJSON(response);
if (codes.length == 0) {
$('#' + inputId).val('');
$('span#' + descId).html('');
}
},
error: function (response) {
$('#' + inputId).val('');
$('span#' + descId).html('');
}
});
},
position: { my : "left top", at: "left bottom" }
});
}

Categories