$.post to PHP file - callback not being hit till containing loop finished? - javascript

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?

Related

Passing JS variable value to PHP variable to update database

If you want to see the part where I tried AJAX, go look down below. It completely messed up the page and I'm stuck on how to do this. I've got some code here:
$id = $_SESSION["id"];
$sql = "SELECT riskcoin FROM klanten WHERE id='$id'";
$INFO=mysqli_query($conn, $sql);
if (mysqli_num_rows($INFO) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($INFO)) {
echo "riskcoin: " . $row["riskcoin"]. "<br>";
$riskcoins = $row["riskcoin"];
}
} else {
echo "0 results";
}
?>
var dealerHand = [];
var playerHand = [];
var currentHand;
var deck;
var deckCount;
var countCards = true;
var bets = new Bets();
// Bets Object
function Bets() {
this.pot = <?php echo "$riskcoins"; ?>;
this.bet = 0;
$('#bet').text(0);
$('#pot').text('$' + this.pot);
}
// Bets methods
Bets.prototype.updateAmounts = function () {
$('#bet').text('$' + this.bet);
$('#pot').text('$' + this.pot);
};
Bets.prototype.doubleDown = function() {
this.pot -= this.bet;
this.bet += this.bet;
};
Bets.prototype.potAmount = function() {
return this.pot;
};
Bets.prototype.betAmount = function(){
return this.bet;
};
Bets.prototype.disableDeal = function () {
$('#button-deal').addClass('disabled');
};
Bets.prototype.addBet = function(amount) {
if (this.pot >= amount) {
this.pot = this.pot - amount;
this.bet = this.bet + amount;
this.updateAmounts();
$('#button-deal').removeClass('disabled');
} else {
notEnoughChips();
}
};
First part is php second part js. I have an int value in my database called riskcoin. this.pot contains that riskcoin value (//Bets object) and shows itin another php file in a paragraph with id="pot".
When an image is clicked another function ads an amount to the bet depending on the picture (for example 5).
Now my question: after the line this.updateAmounts(); it executes
// Bets methods
Bets.prototype.updateAmounts = function () {
$('#bet').text('$' + this.bet);
$('#pot').text('$' + this.pot);
Now my question would be if I could update the riskcoin value in my database with an update query after this function with the current this.pot value? It should show live updates without page refreshes. I've read about AJAX so I tried something like this:
Bets.prototype.updateAmounts = function () {
$('#bet').text('$' + this.bet);
$('#pot').text('$' + this.pot);
window.history.pushState('page2', 'Title', '?coins=' + this.pot);
$(document).ready(function(){
var url = window.location.href;
var params = url.split('?coins=');
var id = (params[1]);
$("#button-deal").click(function(){ $.ajax({
type:"POST",
url:"blackjackgame.php",
data:{id:id},
success:function(result){
$("#pot").html(result);
}
});
});
});
};
But it for some reason when I click on the deal button (#button-deal) it shows up my login page in the middle of the page under all the other stuff, console gives me: GET http://riskybusiness.nglyceum.eu/games/login.css net::ERR_ABORTED 404 (Not Found)jquery-3.1.1.js:5921
PHP and Javascript execute in different contexts. PHP on the server, Javascript on the client (browser). Keep your PHP code and Javascript separate. Since PHP executes first on the server, you can embed PHP output into your HTML/Javascript/CSS—BEFORE—it is sent to the browser.
One problem you have with your code is intermingling PHP and Javascript, such as:
<?php
if (mysqli_num_rows($INFO) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($INFO)) {
echo "riskcoin: " . $row["riskcoin"]. "<br>";
$riskcoins = $row["riskcoin"];
}
} else {
echo "0 results";
}
?>
var dealerHand = [];
var playerHand = [];
var currentHand;
// Bets Object
function Bets() {
this.pot = <?php echo "$riskcoins"; ?>;
this.bet = 0;
$('#bet').text(0);
$('#pot').text('$' + this.pot);
}
The PHP (only) gets processed on the server, and this text is sent to the client:
riskcoin: 100<br>
var dealerHand = [];
var playerHand = [];
var currentHand;
// Bets Object
function Bets() {
this.pot = 100;
this.bet = 0;
$('#bet').text(0);
$('#pot').text('$' + this.pot);
}
Also, this $("#button-deal").click(function(){ in your code adds a click event handler to your button. The problem is, you're not adding this event handler until addBet() is executed, which then executes updateAmount(). Not only don't wait, but the handler is added each time addBet() is executed. Instead add the event handler on page load.
I've separated the various code components into server-side execution and client-side execution contexts, and properly connected them to each other:
var dealerHand = [];
var playerHand = [];
var currentHand;
var deck;
var deckCount;
var countCards = true;
var bets = new Bets();
// Bets Object
function Bets() {
this.pot = 100; // <?=$riskcoin?>;
this.bet = 0;
$('#bet span').text('$' + 0);
$('#pot span').text('$' + this.pot);
$('#deal button').addClass('disabled');
}
// Bets methods
Bets.prototype.updateAmounts = function() {
$('#bet span').text('$' + this.bet);
$('#pot span').text('$' + this.pot);
};
Bets.prototype.potAmount = function() {
return this.pot;
};
Bets.prototype.betAmount = function(){
return this.bet;
};
Bets.prototype.addBet = function(amount) {
if (this.pot >= amount) {
this.pot = this.pot - amount;
this.bet = this.bet + amount;
this.updateAmounts();
$('#deal button').removeClass('disabled');
} else {
notEnoughChips();
}
};
// add the click event handler on page load
document.querySelector("#deal button").addEventListener("click", evt => {
$.ajax({
type: "POST",
url: "deal.php", // <-- post data to separate PHP file, see PHP file below
data: {bet: bets.betAmount()},
success: function(result) {
const win = (result > bets.pot)? " (won)": " (lost)";
bets.pot = result;
bets.bet = 0;
$("#pot span").text('$' + bets.pot + win);
$('#bet span').text('$' + bets.bet);
$('#deal button').addClass('disabled');
}
});
});
document.querySelectorAll("#bet button").forEach(btn => {
btn.addEventListener("click", evt => {
bets.addBet(parseInt(evt.target.textContent));
});
});
function notEnoughChips() {
alert("Not enough chips.");
}
// mock ajax, remove in real world
$.ajax = (function () {
return function (params) {
if (Math.random() < 0.5) {
params.success(bets.pot + (params.data.bet * 2));
} else {
params.success(bets.pot);
}
};
}());
.disabled {
cursor: not-allowed;
pointer-events: none;
color: #c0c0c0;
background-color: #ffffff;
}
<!-- uncomment in the real world
<?php
$id = $_SESSION["id"];
$sql = "SELECT riskcoin FROM klanten WHERE id=?"; // <-- use prepared statements
$INFO=mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
if (mysqli_num_rows($INFO) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($INFO)) {
$riskcoin = $row["riskcoin"];
}
} else {
$riskcoin = 0;
}
?>
-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="pot">Pot: <span><?=$riskcoin?></span></div>
<div id="bet">Bet: <span>0</span> <button>+5</button><button>+10</button><button>+15</button><button>+20</button></div>
<div id="deal"><button>Deal</button></div>
deal.php (The JQuery ajax function POSTs to this file.)
<?php
// this file called in JQuery ajax function found in "#deal button" "click" handler
$id = $_SESSION["id"];
$bet = $_POST["bet"];
$sql = "SELECT riskcoin FROM klanten WHERE id= ?";
$INFO=mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "i", $id);
mysqli_stmt_execute($stmt);
if (mysqli_num_rows($INFO) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($INFO)) {
$riskcoin = $row["riskcoin"];
}
} else {
$riskcoin = 0;
}
// random win or lose
$riskcoin += ((bool)random_int(0, 1))? ($bet * 2): (-1 * abs($bet));
$sql = "UPDATE klanten SET riskcoin = ? WHERE id = ?";
$INFO=mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, "ii", $riskcoin, $id);
mysqli_stmt_execute($stmt);
echo $riskcoin;
?>
// Bets Object
function Bets() {
this.pot = <?php echo "$riskcoins"; ?>;
this.bet = 0;
$('#bet').text(0);
$('#pot').text('$' + this.pot);
}
You cannot put php code inside of javascript as PHP is server side so it runs before javascript.
I believe your best option would be to use php for all of it.

Splitting an AJAX call which returns 5000 rows into multiple AJAX calls with 100 rows

I have a ajax call, and I am loading the data returned into a datatable
Here is my jquery ajax call
<script type="text/javascript">
var oTable;
$(document).ready(function() {
window.prettyPrint() && prettyPrint();
$('#load').click(function()
{
var v = $('#drp_v').val();
var cnt = $('#drp_cnt').val();
var ctg = $('#drp_ctg').val();
var api = $('#drp_api').val();
var nt = $('#drp_nt').val();
$.post("ajax.php",
{ 'version':v,'category':ctg,
'country':cnt,'network_id':nt,
'api':api,'func':'show_datatable'},
function(data)
{
var aColumns = [];
var columns = [];
for(var i = 0; i < data.length; i++)
{
if(i>0)
break;
keycolumns = Object.keys(data[i]);
for(j = 0; j < keycolumns.length; j++)
{
if($.inArray(keycolumns[j],aColumns.sTitle)<=0)
{
aColumns.push({sTitle: keycolumns[j]}) //Checks if
columns.push(keycolumns[j]) //Checks if
}
}
}
var oTable = $('#jsontable').dataTable({
"columns":aColumns,
"sDom": 'T<"clear">lfrtip',
"oTableTools": {
"aButtons": [
{
"sExtends": "csv",
"sButtonText": "CSV",
}
]
}
});
oTable.fnClearTable();
var row = []
for(var i = 0; i < data.length; i++)
{
for(var c = 0; c < columns.length; c++)
{
row.push( data[i][columns[c]] ) ;
}
oTable.fnAddData(row);
row = [];
}
},'json');
});
});
</script>
And here's my php function
function show_datatable($version,$ctg,$cnt,$nt,$api)
{
$cnt_table = "aw_countries_".$version;
$ctg_table = "aw_categories_".$version;
$off_table = "aw_offers_".$version;
$sizeof_ctg = count($ctg);
$cond_ctg = " ( ";
for($c = 0; $c < $sizeof_ctg ; $c++)
{
$cond_ctg = $cond_ctg." $ctg_table.category = '".$ctg[$c]."' ";
if($c < intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." OR ";
else if($c == intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." ) ";
}
$sizeof_cnt = count($cnt);
$cond_cnt = " ( ";
for($cn = 0; $cn < $sizeof_cnt ; $cn++)
{
$cond_cnt = $cond_cnt." $cnt_table.country = '".$cnt[$cn]."' ";
if($cn < intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." OR ";
else if($cn == intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." ) ";
}
$sizeof_nt = count($nt);
$cond_nt = " ( ";
for($n = 0; $n < $sizeof_nt ; $n++)
{
$cond_nt = $cond_nt." $off_table.network_id = '".$nt[$n]."' ";
if($n < intval($sizeof_nt-1))
$cond_nt = $cond_nt." OR ";
else if($n == intval($sizeof_nt-1))
$cond_nt = $cond_nt." ) ";
}
$sizeof_api = count($api);
$cond_api = " ( ";
for($a = 0; $a < $sizeof_api ; $a++)
{
$cond_api = $cond_api." $off_table.api_key = '".$api[$a]."' ";
if($a < intval($sizeof_api-1))
$cond_api = $cond_api." OR ";
else if($a == intval($sizeof_api-1))
$cond_api = $cond_api." ) ";
}
$output = "";
$sql = "SELECT *
FROM $off_table,$cnt_table,$ctg_table
WHERE $off_table.id = $cnt_table.id
AND $off_table.id = $ctg_table.id
AND ".$cond_api."
AND ".$cond_nt."
AND ".$cond_cnt."
AND ".$cond_ctg;
$result = mysql_query($sql);
$arr_result = array();
while($row = mysql_fetch_assoc($result))
{
$arr_result[] = $row;
}
$arr_result_enc = json_encode($arr_result);
echo $arr_result_enc;
}
Now, I want to modify this code. Say I want to work it like this:
I will call for v, and the AJAX will send me 100 rows once, then again 100 rows and then again 100 rows.
I mean splitting the AJAX call to returns chunks of all the data one after another. Say something like there will be multiple times when the AJAX will be called, and each time it will send me 100 chunks of data.
While the work will be going on, there will be a progress bar with a cancel button.
If I click the cancel button, then if 3 times the AJAX function have been called, it will show me 300 data and then the AJAX will be stopped. The database will show only 300 data.
JQ:
// counter that allows you to get a new set of rows
var step = 0;
// set variable if you want to restrict the number of rows will be loaded
var maxStep = 0;//
// how many rows should be returned
var count = 100;
// if the cancel button is pressed
var cancel = false;
$(function() {
$('#load').click(function(){
getData();
})
$('#cancel').click(function(){
cancel = true;
})
});
function getData()
{
step++;
//If cancel variable is set to true stop new calls
if(cancel == true) return;
// checks if the variable is set and limits how many rows to be fetched
if(maxStep >0 and step >= maxStep) return;
$.post('ajax.php'
,{
'step':step,
'count':count,
}
,function(data, textStatus, jqXHR){
// do something with the data
// when it finishes processing the data, call back function
getData();
}
,'json'
)
}
AJAX.PHP
$step = 0;
if(isset($_POST['step'])) $step = (int)$_POST['step'];
$count = 0;
if(isset($_POST['count'])) $count = (int)$_POST['count'];
if($step>0 and $count>0)
{
$offset = ($step-1) * $count;
$limit = $offset.','.$count;
// --------------
// your code here
// --------------
$sql = "SELECT *
FROM $off_table,$cnt_table,$ctg_table
WHERE $off_table.id = $cnt_table.id
AND $off_table.id = $ctg_table.id
AND ".$cond_api."
AND ".$cond_nt."
AND ".$cond_cnt."
AND ".$cond_ctg."
LIMIT ".$limit;// <- limit
$result = mysql_query($sql);
$arr_result = array();
while($row = mysql_fetch_assoc($result))
{
$arr_result[] = $row;
}
$arr_result_enc = json_encode($arr_result);
echo $arr_result_enc;
// echo rows
echo json_encode($rows);
}
Here's a heavy refactoring of the client-side code, in which the overall process is split into into three separate functions getBatch(), makeRows() and showData(), and kicked off by a very modified version of the original click handler.
Batching is controlled by getBatch(), which makes a ajax requests with two extra params - start and batchSize. These instruct the server-side script which batch of data to return.
makeRows() and showData() are just synchronous worker functions called by getBatch().
I have assumed that progress is reported in a DOM element "#progress"`. You can report what you like here. I've kept it simple, showing the accumulated row count. By adding a batch counter, you could also show the number of completed batches.
Cancellation is achieved by setting outer var allowBatch to false. The currently requested batch will continue to be found but permission to retrieve further batches is withdrawn.
For good measure various DOM elements are enabled/disabled or shown/hidden at the start and end of the process. This can be omitted if not required.
var oTable;
$(document).ready(function() {
window.prettyPrint() && prettyPrint();
var aColumns = [],
columns = [],
rows = [],
$progress = $("#progress"),
allowBatch;
function getBatch(options) {
return $.post("ajax.php", options, 'json').then(function(data) {
var promise;
if(allowBatch && data && data.length) {
$progress.text(makeRows(data));
options.start += batchsize;
promise = getBatch(options);
} else {
promise = $.when(showData());
}
return promise;
});
}
function makeRows(data) {
var keycolumns, i, j;
if(aColumns.length == 0) {
keycolumns = Object.keys(data[0]);
for(j = 0; j < keycolumns.length; j++) {
if($.inArray(keycolumns[j], aColumns.sTitle) <= 0) {
aColumns.push({sTitle: keycolumns[j]});
columns.push(keycolumns[j]);
}
}
}
for(i = 0; i < data.length; i++) {
rows.push( columns.map(function(col) {
return data[i][col];
}) );
}
return rows.length;
}
function showData() {
var oTable = $('#jsontable').dataTable({
'columns': aColumns,
'sDom': 'T<"clear">lfrtip',
'oTableTools': {
"aButtons": [{
"sExtends": "csv",
"sButtonText": "CSV"
}]
}
});
oTable.fnClearTable();
$.each(rows, function(row) {
oTable.fnAddData(row);
});
return oTable;
}
$('#load').on('click', function(e) {
e.preventDefault();
var $load = $(this).attr('disabled', true),
$cancel = $("#cancel").show();
$progress.text('').show();
aColumns.length = columns.length = rows.length = 0;
allowBatch = true;
getBatch({
'version': $('#drp_v').val(),
'category': $('#drp_ctg').val(),
'country': $('#drp_cnt').val(),
'network_id': $('#drp_nt').val(),
'api': $('#drp_api').val(),
'func': 'show_datatable',
'start': 0,
'batchsize': 100
}).then(function(oTable) {
// ... all done
$load.attr('disabled', false);
$cancel.hide();
$progress.hide();
});
});
$("#cancel").on('click', function(e) {
e.preventDefault();
allowBatch = false;
}).hide();
$("#progress").hide();
});
Tested only for parse errors, so may need to be debugged
You will still need to modify the server-side script to accept the two additional parameter start and batchsize and compose its SQL accordingly. That should be fairly trivial.
The part I'm most uncertain about is makeRows(), which I struggled with slightly. If nothing works, look there first.

Making an ajax request with jsonp(no jquery)

I need some help on an assignment that I need to do. Basically the question is a number guessing game. We're assigned a number in the interval [0,1023] based on our student number and we have 11 guesses to get the right number. I know I have to use a binary search to get the number, my only problem is connecting to the server and getting a result.
We're given this:
A sample request looks as follows:
http://142.132.145.50/A3Server/NumberGuess?snum=1234567&callback=processResult&guess=800
And also given that the request returns the following parameters:
1: A code to determine if your guess is equal, less than or greater than the number
2: Message string
3: Number of guesses made by my application
This is what I've tried so far, just as a test to get the server request working. All I get in return is "object HTMLHeadingElement"
window.onload = function() {
newGuess();
}
function newGuess() {
var url = "http://142.132.145.50/A3Server/NumberGuess?snum=3057267&callback=processResult&guess=600";
var newScriptElement = document.createElement("script");
newScriptElement.setAttribute("src", url);
newScriptElement.setAttribute("id", "jsonp");
var oldScriptElement = document.getElementById("jsonp");
var head=document.getElementsByTagName("head")[0];
if (oldScriptElement == null) {
head.appendChild(newScriptElement);
} else {
head.replaceChild(newScriptElement, oldScriptElement);
}
}
function processResult(code,message,guesses) {
var code = document.getElementById("code");
var message = document.getElementById("message");
var guesses = document.getElementById("guesses");
code.innerHTML = code;
message.innerHTML = message;
guesses.innerHTML = guesses;
}
EDIT: Current state of my code.
window.onload = function() {
min = 0;
max = 1023;
mid = 0;
setInterval(newGuess,1000);
};
function newGuess() {
mid = Math.floor((max-min)/2);
var url = "http://142.132.145.50/A3Server/NumberGuess?snum=3057267&callback=processResult&guess="+mid;
var newScriptElement = document.createElement("script");
newScriptElement.setAttribute("src", url);
newScriptElement.setAttribute("id", "jsonp");
var oldScriptElement = document.getElementById("jsonp");
var head=document.getElementsByTagName("head")[0];
if (oldScriptElement == null) {
head.appendChild(newScriptElement);
} else {
head.replaceChild(newScriptElement, oldScriptElement);
}
}
function processResult(codeJ,messageJ,guessesJ) {
code = document.getElementById("code");
message = document.getElementById("message");
guesses = document.getElementById("guesses");
code.innerHTML = codeJ;
message.innerHTML = messageJ;
guesses.innerHTML = guessesJ;
if(codeJ == 0){
return;
}else if(codeJ == -1){
min = mid + 1;
}else if(codeJ == 1){
max = mid -1;
}
console.log(mid);
}
Check your variable-names. You are overwriting the function-patameters.
Something like
code.innerHTML = code;
message.innerHTML = message;
guesses.innerHTML = guesses;
just CAN'T work, you should see the problem yourself...

Ajax's PHP into while just working once

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) {
..
..
.

Transfering php variables to javascript variables in a php function

I'm trying to transfer php variables, that I have pulled out of a database, into three different javascript arrays. I use a php function to dynamically create a css dropdown menu, and then use a php loop to transfer the php variables into the javascript arrays. I then try to use a javascript function to initialize the attributes of the css menu. The same function is called from each of the links of the menu to update the menu based on the javascript arrays.
Here is the php function:
function createMenu()
{
//create the proper drop down menu, based on the total number of games played and the max number of games
$totalVods = count($this->VodID);
$menuArray = array();
for($i = 0; $i < $totalVods; ++$i)
{
if ($this->currentVodID != $i)
{
$menuArray[] = ($i+1);
}
}
if ( $totalVods < $this->MaxGames )
{
for ($i = $totalVods; $i < $this->MaxGames; ++$i)
{
$menuArray[] = ($this->currentVodID+1);
}
}
$totalGames = count($menuArray);
printf("<p>$this->Name</p>");
printf("<div id='cssmenu2'>");
printf('<ul>');
if ($menuArray)
{
printf('<li id="vod1" class="has-sub last"><span></span><img class="arrow" src="/images/Arrow.png">');
printf('<ul>');
if ($totalGames > 1)
{
for ($j = 0; $j < ($totalGames - 1); ++$j)
{
$vodNum = 'vod'. ($j+2);
printf("<li id='$vodNum' onclick=''><span></span></li>");
}
}
$vodNum = 'vod'. ($totalGames + 1);
printf("<li id='$vodNum' class='last' onclick=''><span></span></li>");
printf('</ul>');
}
else
{
printf('<li id="vod1"><span>Game 1</span>');
}
printf('</li>');
printf('</ul>');
printf('</div>');
//---------------------------------------------------
// function works fine up till here
// ------------------------------------------------
printf('<script>');
printf('alert("Right after totalGames");'); /* If I take this part out, up till the next comment, the rest works, but none of this part, even the alerts, works */
for($i = 0; $i < $totalVods; ++$i)
{
printf("vodName[$i] = 'Game ". ($i + 1) ."';");
printf("alert('vodName[$i]= '+vodName[$i]);");
$this->VodObject->selectVod($this->VodID[$i]);
$address = $this->VodObject->returnVod();
printf("vodAddress[$i] = '$address';");
$date = $this->VodObject->returnDate();
printf("vodDate[$i] = '$date';");
}
if ($totalVods < $this->MaxGames )
{
for ($i = $totalVods; $i < $this->MaxGames; ++$i)
{
printf("vodName[$i] = 'Game ". ($i + 1) ."';");
$gameNum = $i +1;
$address = "<div class='matchNoVOD'>There is no Game $gameNum<br />Series ended before this game.</div>";
printf("vodAddress[$i] = '$address';");
printf("vodDate[$i] = '';");
}
}/* End of the section that is having problems- if I take this out, the rest of the alerts work */
printf('alert("Right before window.onload");');
printf('window.onload = function() { switchVod(0); };');
printf('</script>');
}
In the javascript part of the above function, I access a php class called vodObject- that just accesses the database and returns the strings I want to place in the javascript array.
The javascript function that updates the css menu is placed in the part of the html, and looks like this:
<script>
var vodName = Array();
var vodAddress = Array();
var vodDate = Array();
function createfunc(i)
{
return i;
}
function switchVod(vodID)
{
alert("switchVod ran");
alert('vodID= ' + vodID);
var x=document.getElementById("vod1");
var y = x.getElementsByTagName("span");
y[0].innerHTML = vodName[vodID];
for (var i=0; i < vodName.length; i++)
{
if ( i != vodID)
{
var id = createfunc(i);
var gameNum = i + 2;
var gameID = "vod" + gameNum;
var x = document.getElementByID(gameID);
var y = x.getElementsByTagName("span");
y[0].innerHTML = vodName[i]
x.onclick = function() { switchVod(id); }
}
}
alert("after for loop");
alert("1");
document.getElementById('vodObj').innerHTML = vodAddress[vodID];
alert("2");
document.getElementById("vodDate").innerHTML = vodDate[vodID];
alert("finished");
}
</script>
The createfunc(i) is meant to get around the closure issues I heard about.
Any ideas about what I can try to fix my code? Thank you for your help, in advance!
In the JS code, you can just use var city = '<?=$city;?>';, for example.
If I got you right, you can make it using AJAX. The PHP file while print this:
echo json_encode($your_php_array);
Then, using JQuery $.getJSON method
$.getJSON('json.php', function(response) {
/* do your stuff here */
console.log(response); // This var has the json object
});
Let me know if it's useful.

Categories