I have a loop from an array and what it does is before saving it in datatable it will check if the item exsist in database and here is the code
for (i = 0, len = array.length; i < len; i++) {
var item_code = array[i][1];
var description = array[i][2];
var qty = array[i][0];
if (item_code != "") {
console.log(item_code);
var if_exsist = function () {
var tmp = null;
$.ajax({
url: "../program_assets/php/web/stocks_excel_insert_transactions.php",
data: {
saving_mode : 'check_item',
item_code : item_code
},
'async': false,
type: 'post',
success: function (data) {
var data = data.trim();
if (data == 0) {
tmp = "no"
$('#btn_save').prop('disabled', true);
} else {
tmp = "yes"
}
}
});
return tmp;
}();
tbl_delivery_list.row.add({
"docket_number" : docket_number,
"from" : from,
"from_id" : from_id,
"to" : to,
"to_id" : to_id,
"item_code" : item_code,
"description" : description,
"qty" : comma(qty),
"exsist" : if_exsist
}).draw( false );
counter++;
}
}
the code above will work but my problem is how can I incorporate a progress bar? loading sample. I add this code but the loading happens after all the work has been done.
progress = counter / array.length;
progress = progress * 100;
$(".bar").css("width", progress + "%");
my target here is to update the progress bar one by one after doing the code on the 1st one
Related
6 items are added onload using ajax. Each click, 6 items are being appended.
I want to hide #load-more button if newly added items are less than 6.
How to find the count of newly added items?
I use .length but all items are being counted.
Thanks for your help.
var max = 6;
var NewItems = $(".items").length;
if (NewItems > max) {
$("#load-more").hide();
} else {
$("#load-more").show();
}
var max = 6;
var start = 1;
var winloc = window.location;
$(window).bind('hashchange', function() {
if (winloc.hash === "" || winloc.hash === "#home") {
homeurl = `https://mailliw88.blogspot.com/feeds/posts/default?start-index=${start}&max-results=${max}&alt=json-in-script`;
loadList(homeurl);
}
}).trigger('hashchange')
function more() {
start += max;
loadList(`https://mailliw88.blogspot.com/feeds/posts/default?start-index=${start}&max-results=${max}&alt=json-in-script`);
}
function loadList(url) {
$.ajax({
url: url,
type: 'get',
dataType: "jsonp",
success: function(data) {
if (data.feed.entry) {
datas = data.feed.entry;
var entry = data.feed.entry;
for (var i = 0; i < entry.length; i++) {
postTitle = entry[i].title.$t;
items = '<div class="items"><h2>' + postTitle + '</h2></div>';
document.getElementById('showlists').innerHTML += items;
}
}
var newItems = $(".items").length;
if (newItems > max) {
$("#load-more").hide();
} else {
$("#load-more").show();
}
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='showlists'></div>
<div id='load-more' onclick="more()">
load more
</div>
Change:
var newItems = $(".items").length;
if (newItems > max) {
To:
if (data.feed.entry.length < 6)
The variable "max" will be out of scope for your "success" method since it's defined outside of it and is an integer type, so you will need to either directly add it, or use an object, like:
var max = {entries: 6};
...
if (data.feed.entry.length < max.entries)
You could add data attributes to the new items with an incrementing id so the final html would look like
<div data-load="1"></div>
<div data-load="1"></div>
...
<div data-load="2"></div>
...
and then in you're js
$(`div[data-load="${Math.max(...$('div').map(item => parseInt(item.attr("data-load"))))}"`)
would get all the latest ajax elements
I need to get the emailid value from one json formated list the list is like i mentioned below
result:::[{name=sudersan san, emailid=divya.vairavel#gmail.com}, {name=Sasi Guru, emailid=ragavendran.kesavan#gmail.com }]
so please guys suggest me how can i get the emailid from above
i have tried the code in javascript for splitting.
if(data1.length >0 ){
for (var k = 0; k < data1.length; k++) {
var emailid= data1[k].emailid
var intname= data1[k].intname
var datevalue = localStorage.getItem("datevalue");
var sessiontime = localStorage.getItem("sessiontime");
$.ajax({
url: "clientinteractoremail",
type:"POST",
data : {
emailid : emailid,
datevalue : datevalue,
sessiontime : sessiontime,
intname : intname
},
success: function(data1) { },
});
}
}
var result = [
{
name="sudersan san",
emailid="divya.vairavel#gmail.com",
},
{
name="Sasi Guru",
emailid="ragavendran.kesavan#gmail.com",
}]
Those statements pull the values from this:
for(int i = 0 ; i<result.length;i++){
console.log(result[i].name);
console.log(result[i].emailid);
}
you try this
//an ajax call to the api
jQuery(document).ready(function() {
jQuery.ajax({
url:"http://localhost:8080/activitiesWithRealData?location=%22SEA%22&startDate=%2205-14-16%22&endDate=%2205-16-16%22&theme=%22food%22",
dataType: 'JSON', type: 'GET',
success: function (data)
var viewModel;
if(data) {
viewModel = new dealsPageModel(data);
var idList = "";
for (var i = 0; i< data.packageDeal.length; i++)
{
if (i == data.packageDeal.length -1)
{ idList += data.packageDeal[i].hotelId;
}
else
{idList += data.packageDeal[i].hotelId + ',';
}
}
var searchUrl = "http://terminal2.expedia.com/x/hotels?hotelids=" + idList + "&apikey=6weV4ksGIJ5eQhd58o2XTDwVo35lZf2S";
//another call to another api to return hotel specific info
jQuery.get(searchUrl, function ( )
{
for(var i=0; i<viewModel.dealList.length; i++)
{
var hotelId = viewModel.dealList[i].hotelId;
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = HotelInfoList.HotelInfo[i].Name;
}
// Get the hotelid from the current deal
// Loop through the hotelinfolist.hotelInfo and find out the url for the hotel idList
//Loop through the hotelinfolist.hotelInfo and find out the name for the hotel
viewModel.dealList.push(new deal(data.packageDeal[i], url, name));
}
ko.applyBindings(viewModel);
});
}
}
})
});
You loop through data.HotelInfoList.HotelInfo but operate on HotelInfoList.HotelInfo[i].ThumbnailUrl. The data. at the beginning is missing.
Also, place data in the callback function in jQuery.get:
jQuery.get(searchUrl, function(data){
// …
your data is in data.HotelInfoList not in HotelInfoList
your loop should be like this
for(var i=0; i<data.HotelInfoList.HotelInfo.length; i++)
{
var url = data.HotelInfoList.HotelInfo[i].ThumbnailUrl;
var name = data.HotelInfoList.HotelInfo[i].Name;
}
The code i'm trying to get to work is part of a price list of products from a db. It works almost all of it but i need one ajax to run multiple times, and it does, it even runs the success sentences but when i check the db its like it just ran once... i hope you can help me.
I take 2 values from inputs which are id and amount of the product, and i add them to the list when a button calls the send function, this is that part of the code:
function valores(cod, cant) {
if (cod != '') {
cot.push([cod, cant]);
i++;
}
return cot;
}
function send () {
event.returnValue=false;
var id = $('#id').val();
var amount = $('#cant').val();
var total;
if ($('#total').length > 0) {
total = document.getElementById('total').value;
} else {
total = 0;
}
$.ajax({
type: 'POST',
data: ({cod : id, cant : amount, tot : total }),
url: 'process/agprods.php',
success: function(data) {
$('#totals').remove();
$('#prodsadded').append(data);
valores(id, amount);
rs = $(document.getElementById('rs').html);
},
error: function () {
$('#rs').innerHTML = rs;
document.getElementById('note').innerHTML = "Error: The product doesn't exist.";
$('#handler-note').click();
}
});
}
(I translated some words to english that are originaly in spanish and to make it more readable to you)
So, the cot[] array keeps the product's id and amount, to use them in the next code, which runs when the list is complete and you hit a save button that calls this function:
function ncotiza () {
event.returnValue=false;
var nlist = $('#codp').val();
var day = $('#days').val();
$.ajax({
async: false,
type: 'POST',
data: ({listnumber: nlist, days : day}),
url: 'process/ncot.php'
});
j = 0;
while (j <= i) {
if (cot[j][0] != 0 && cot[j][1] != 0) {
var num = cot[j][0];
var cant = cot[j][1];
$.ajax({
async: false,
type: 'POST',
data: ({ listnumber : nlist, prodid: num, amount : cant }),
url: 'process/ncotpro.php',
success: function () {
alert('Success');
}
});
cot[j][0] = 0;
cot[j][1] = 0;
j++;
}
if (j == i) {
window.location.reload(1);
alert("Finished Successfully");
};
}
}
And it all runs fine, here's the PHP:
(ncot.php)
$listnumber = isset($_POST["listnumber"]) ? $_POST["listnumber"] : '';
$days = isset($_POST["days"]) ? $_POST["days"] : '';
$cons = "INSERT INTO pricelist (listnumber, diashabiles, cdate)
VALUES ('$listnumber', '$days', CURDATE())";
mysql_query($cons);
?>
(ncotpro.php)
$listnumber = isset($_POST["listnumber"]) ? $_POST["listnumber"] : '';
$prodid = isset($_POST["prodid"]) ? $_POST["prodid"] : '';
$amount = isset($_POST["amount"]) ? $_POST["amount"] : '';
$cons = "SELECT price, um
FROM inventory
WHERE listnumber = ".$prodid;
$result = mysql_query($cons) or die ("Error: ".mysql_error());
$row=mysql_fetch_assoc($result);
$umcons = mysql_query("SELECT uvalue FROM um WHERE id = ".$row["um"]) or die ("Error:".mysql_error());
$umres = mysql_fetch_assoc($umcons);
$vuum = $umres["uvalue"];
$fprice = $row["price"] * ($amount * $vuum);
$cons = "INSERT INTO cotpro (cotizacion, producto, amount, monto)
VALUES ('$listnumber', '$prodid', '$amount', '$fprice')";
mysql_query($cons) or die ("Error: ".mysql_error());
?>
The first ajax runs ok, then it also does the one that's inside the while, and it throw all the alerts but when i check the db it just made 1 row and not all it has to.
I'm sorry if it's too obvious or something, i've look a lot of questions and answers in this page and i've been trying to fix this for hours but i just dont see it.
Thank you beforehand.
Try to debug the 2nd jquery file via firebug.
what the value you return in i
while (j <= i) {
..
..
.
I am having a problem with a block of my code, this section creates boxes of chocolates based on what a user chooses in a previous step and what data is pulled from the database in the api script.
the problem is that it doesn't work without the alert('hi') in it. if i take that out it will just create an empty box without dropping the flavors in it, the flavor the flavors are inserted with the createFlavorArray function.
var product = new Array();
var price = new Array();
var size = new Array();
$(function () {
$.ajax({
type: 'POST',
url: 'phpscripts/api.php',
data: "",
dataType: 'json',
success: function(rows)
{
count = 0;
for (var i in rows)
{
var row = rows[i];
product[count] = row[0];
price[count] = row[1];
size[count] = row[2];
count++;
}
}
});
});
//b = box
//o = option that is inside the box
//nextBoxId is the box id
//nextFlavorId is the option or flavor id
var nextBoxId = 1;
var nextFlavorId = 1;
var orderCap = 0;
var subTotal = 0;
var numOfChocolates = 0;
var numOfBoxes = 0;
$(document).ready(function(){
while (halfPoundBoxes > 0) {
$("#boxes").append('<div id="b'+nextBoxId+'"></div>');
$('#b'+nextBoxId).addClass('div-table-selection');
$('#b'+nextBoxId).append($('#minusBox').clone().attr('id', "m"+nextBoxId));
$('#b'+nextBoxId).append('<div style="display:table-row"></div>');
//call the function to loop through and create the number of flavor options needed
var x = 0;
alert('hi');
while(x < product.length){
if ('1/2lb Box' == product[x]) {
createFlavorArray(size[x], nextBoxId);
subTotal += price[x] * 1;
$('#b'+nextBoxId).attr('title', product[x]);
}
x++;
}
//clone the delete box button and make it visible
$('#m'+nextBoxId).show(500);
$('#b'+nextBoxId).append("<br />");
if (orderCap == 0) {
$('#boxes').append('<div id="msg"><p>If you wish to add another box to your order select the size and click +1 Box.</p></div>');
}
$("#m"+nextBoxId).click(function() {
$(this).parent().remove();
orderCap--;
//if they're ordering zero boxes hide the order button
//remove total price
//remove the message
if (orderCap == 0)
{
document.getElementById('orderBtn').style.display = "none";
$("#msg").remove();
$("#totalPrice").empty();
}
if (orderCap < 10)
{
$("#cap").remove();
$("#addBox").show(500);
}
var y = 0;
while (y < product.length) {
if ('1/2lb Box' == product[y]) {
subTotal -= price[y] * 1;
numOfChocolates -= size[y] * 1;
}
y++;
}
$('#totalPrice').html("<p>Sub Total: " + subTotal + "</p>")
//subtract the new
$('#finalpaypal').val(subTotal);
});
nextBoxId++;
orderCap++;
numOfBoxes++;
$('#totalPrice').html("<p>Sub Total: " + subTotal + "</p>")
halfPoundBoxes--;
}
The reason your code is working only when using an alert(), is that the alert() action is giving your jQuery AJAX request a few seconds to return a value to your success() call back function.
You should move any code which is affected by your callout function, into the callout function also, so that this code runs in the correct order.
Alternatively you could not run your AJAX request asynchronosly by adding async:false, but as #Rocket has commented, this isn't recommended.
$.ajax({
async: false,
You need to put the code in a function and run it after the ajax success is finished
...
$(function () {
$.ajax({
type: 'POST',
url: 'phpscripts/api.php',
data: "",
dataType: 'json',
success: function(rows)
{
count = 0;
for (var i in rows)
{
var row = rows[i];
product[count] = row[0];
price[count] = row[1];
size[count] = row[2];
count++;
}
do_after_ajax();
}
});
});
function do_after_ajax(){
while (halfPoundBoxes > 0) {
$("#boxes").append('<div id="b'+nextBoxId+'"></div>');
$('#b'+nextBoxId).addClass('div-table-selection');
....
}
It looks like you're trying to operate on markup returned by your ajax. That code needs to be moved into the success callback of the ajax request. The reason the alert call makes it work is simply that it delays everything else long enough for the page to finish loading.