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) {
..
..
.
Related
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
I am trying to run a specific for loop every x seconds, but cannot seem to make `setInterval work. I am sure my syntax is incorrect, yet, I cannot seem to get it right.
I have added my full code below:
jQuery:
//Click saves this.id as userID
$(function() {
var rTitle, rText, qTitle, qText, numRows, userID;
$("#buttons").find(".btn").click(function() {
$(this).parent().toggleClass('fullscreen');
$(this).parent().siblings().toggleClass('master');
var userID = this.id;
//userID is then used for ajax to PHP script, information passed back is put in variables and generateProblems function is run
$.ajax({
type: "POST",
url: 'include/responseget.php',
dataType: 'json',
data: {
userID: userID
},
success: function(json) {
rTitle = json.rTitle;
rText = json.rText;
qTitle = json.qTitle;
qText = json.qText;
next = json.next;
numRows = json.numRows;
id = json.id;
generateProblems();
}
});
});
//Generate draggable html with an interval of 1000
function generateProblems() {
$('<div>' + qTitle + '</div>').data('number', qTitle).attr('id', 'question').attr('class', 'bold').appendTo($("#" + id).parent()).hide().fadeIn(2000);
for (var i = 0; i < numRows; i++) {
setInterval(function() {
$('<div>' + rTitle[i] + '</div>').data('number', next[i]).attr('id', +next[i]).appendTo($("#" + id).parent()).draggable({
containment: '.site-wrapper',
stack: '#testpile div',
cursor: 'move',
revert: true
}).hide().fadeIn(2000)
$('<div>' + rText[i] + '</div>').data('number', next[i]).attr('id', +next[i]).appendTo($("#" + id).parent()).hide().fadeIn(2000);
}, 1000);
}
//Rest of the code is not important, but I put it in nonetheless.
$('#testdrop').droppable({
drop: handleDropEvent,
accept: '#testpile div'
});
function handleDropEvent(event, ui) {
var problemNumber = ui.draggable.data('number');
ui.draggable.draggable('disable');
ui.draggable.draggable('option', 'revert', false);
$("#testpile").children().hide();
$.ajax({
type: "POST",
url: 'include/responseget.php',
dataType: 'json',
data: {
userID: problemNumber
},
success: function(json) {
rTitle = json.rTitle;
rText = json.rText;
qTitle = json.qTitle;
qText = json.qText;
next = json.next;
numRows = json.numRows;
generateProblems();
}
});
}
}
});
PHP:
<?php include 'login.php';
if(isset($_POST['userID'])){
$id = $_POST['userID'];
$stmt = $conn->prepare("SELECT DISTINCT AnswerTitle, AnswerText, QuestionTitle, QuestionText, Next FROM question_answers
INNER JOIN question
ON question_answers.QuestionID=question.QuestionID
INNER JOIN answer
ON question_answers.AnswerID=answer.AnswerID
WHERE AnswerGroup = ?;");
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc())
{
$rTitle_array[] = $row['AnswerTitle'];
$rText_array[] = $row['AnswerText'];
$qTitle = $row['QuestionTitle'];
$qText = $row['QuestionText'];
$next_array[] = $row['Next'];
$numRows = ($result->num_rows);
}
$response = array(
'rTitle' => $rTitle_array,
'rText' => $rText_array,
'qTitle' => $qTitle,
'qText' => $qText,
'next' => $next_array,
'numRows' => $numRows,
'id' => $id
);
echo json_encode($response);
}
// close connection
mysqli_close($conn);
?>
It sounds like you're trying to get this effect of adding one row every second. You could use recursion.
Also, setInterval is for numerous calls. setTimeout is for a single call.
function generateProblems(i)
{
// if we're at the end then stop
if(i == numRows) return;
// wait 1000
setTimeout(function()
{
// do what you want with i here
// call the next iteration
generateProblems(i + 1);
}, 1000);
}
// then you kick it off with the 0 index
generateProblems(0);
Or if you want the first iteration to kick off immediately:
function generateProblems()
{
// if we're at the end then stop
if(i == numRows) return;
// do what you want with i here
// move to next row
++i;
setTimeout(generateProblems, 1000);
}
// global var to keep track of where we are
i = 0;
generateProblems
I'm making a stock table, where the user can input a number of stock to issue out, and this function is to verify, for each member of the table, whether or not the quantity of stock in the database is sufficient to make the issue.
When I breakpoint through the code on Chrome, it seems to never hit the inside code of the $.post until after its finished looping through the table. And by then the data that is supposed to be passed to AddIssue just becomes 1 and 10 and nothing else.
It's starting to drive me mad, so I'd appreciate a pointer on what I'm doing wrong here
var issueArray =[];
function VerifyIssue()
{
var numRows = document.getElementById("searchTable").rows.length - 2;
var running = true;
var str1 = "issue_";
while(running == true)
{
if (numRows < 0 && running == true)
{
running = false;
//insert code for success
break;
}
else if (running == false)
{
break;
}
var str2 = numRows;
var comb = str1.concat(str2);
var issue_element = document.getElementById(comb);
var q = issue_element.value;
var i = issue_element.name;
var idd = i.replace("issue_", "");
var trimId = idd.trim();
$.post
(
'includes/issueCheck.php',
{
id: trimId,
issueQuantity: q
},
function(result)
{
alert(result);
if (result < 0)
{
alert("One of more quantities inputted are greater than held in stock");
running = false;
}
if (result > 0)
{
addIssue(trimId, q);
}
}
);
numRows = numRows - 1;
}
alert(issueArray);
}
function addIssue(issueID, quant)
{
var item = {};
item.label = issueID;
item.value = quant;
issueArray.push(item);
}
This is the PHP that is called by the $.post
<?php
$server = 'SQL2008';
$connectionInfo = array( "Database"=>"rde_470585");
$conn = sqlsrv_connect($server,$connectionInfo);
$false = -1;
$true = 1;
$id = $_POST['id'];
$quantity = $_POST['issueQuantity'];
$query = "Select Quantity FROM Stock WHERE StockID = ?";
$param = array($id);
$res = sqlsrv_query($conn, $query, $param);
$row = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC);
$dbQuantity = $row['Quantity'];
if ($dbQuantity < $quantity)
{
echo $false;
}
else if($dbQuantity >= $quantity)
{
echo $true;
}
Do you realise that your function(result){ ... } will only be called when the server response for your POST request is received? You have to build the code to take that delay into account.
I'm still working on this, reading up on Promises based on what #jojo said, but not sure if it's going to work for me.
How else can I make the javascript wait for a server response before resuming?
I am sending a javascript array by using jquery to a php script.
In ajax I have a myarr variable but this variable can't be accessed in php.
Error is :
Undefined index myarr
Please Please help me. this is really important.
This is my jquery code:
for (var n = 0; n < arraySubId.length; n++) {
var ansArr = [];
for (var m = 1; m <= 11; m++) {
ansArr[m - 1] = $('#' + arraySubId[n] + '-' + m + '').val();
}
* $.ajax({
type: 'POST',
data: ({
'sub_id': arraySubId[n],
'myarr': ansArr
}),
url: 'Scripts/insert_feedback.php',
success: function(data) {
if (data == "1") {
} else {
alert(data);
}
}
}); *
}
When I access myarr variable in php, it's displaying:
Undefined index myarr.
Please Please help me.
And this is my php code:
<?php
session_start();
$prn = $_SESSION['username'];
$sub_id = $_POST['sub_id'];
$ans_arr = $_REQUEST['myarr'];
include 'dbclass.php';
$dbclass = new DBClass;
$mysqli = $dbclass->connect();
$query = "INSERT INTO ".$sub_id."(student_prn, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, date) values('$prn', '$ans_arr[0]','$ans_arr[1]','$ans_arr[2]',
'$ans_arr[3]','$ans_arr[4]','$ans_arr[5]','$ans_arr[6]',
'$ans_arr[7]','$ans_arr[8]','$ans_arr[9]','$ans_arr[10]', now())";
$msg = $dbclass->insert($query);
echo $msg;
?>
Try to convert your array to Json String and send it in JS, and in PHP decode it using json_decode()
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.