How to get a variable value into jQuery / ajax? - javascript

I am trying to get a variable into a jQuery function. I have found many other SO on it but I don't really understand how they would relate to my code or how the syntax works. I am new to JS so I am sure I just don't understand something.
Below I want to get the value of php_file_path_to_call[i] in my ajax call. It can be put in a variable before going into jQuery as it is just in a loop. Could you please show me exactly what the code would be to do this? I have been stuck for many hours! Thanks very much :)
<script>
tb_checkbox_value = 0
tb_js_checkbox_id = '<?php echo $checkbox_id;?>';
no_of_checkboxes_on_page = '<?php echo $no_of_checkboxes_on_page;?>';
counter = '<?php echo $checkbox_counter;?>';
if (counter == 0){
checkbox_element = [];
php_file_path_to_call = [];
// alert("array created")
}
php_file_path_to_call[counter] = '<?php echo $php_file_path_to_call;?>';
js_user_id = '<?php echo $user_id;?>';
temp_checkbox_element = document.getElementById(tb_js_checkbox_id)
checkbox_element.push(temp_checkbox_element)
if (counter == (no_of_checkboxes_on_page - 1)){ //outputs on last loop
alert('if statement counter = ' + counter)
for (i = 0; i <= (no_of_checkboxes_on_page - 1); i++) {
alert('for statement counter = ' + i)
jQuery(checkbox_element[i]).click(function(){
if(jQuery(checkbox_element[i]).prop("checked") == true){
tb_checkbox_value = 1
}
else if(jQuery(checkbox_element[i]).prop("checked") == false){
tb_checkbox_value = 0
}
jQuery.ajax({
type: "POST",
url: php_file_path_to_call[i],
data: {userid: js_user_id, checkbox: tb_checkbox_value},
success: function() {
alert("Success checkbox value: " + tb_checkbox_value + "file path: " + php_file_path_to_call[i])
jQuery('#tb-checkbox-saved').html('SAVED')
setTimeout(function () {
jQuery('#tb-checkbox-saved').html('')
}, 1333);
}
});
});
}
}
</script>

Related

Sending a JavaScript variable to PHP

So I am trying to store the date inside a database and to do so I need to pass the variable 'date' to the PHP file store.pro.php however, I am not sure how to do this. I have tried Ajax but at the moment it doesn't seem to be working.
Javascipt code:
// variables for fetching current date
n = new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
// variables for displaying current date
let displayDay = 0;
let displayMonth = 0;
// If m or d are only one digit, add a leading 0 to the value
if (d < 10) {
displayDay = '0' + d.toString();
} else {
displayDay = d.toString();
}
if (m < 10) {
displayMonth = '0' + m.toString();
} else {
displayMonth = m.toString();
}
// storing the current date within raceDate
var date = displayDay + '/' + displayMonth + '/' + y;
$.ajax({
url: "processes/store.pro.php",
type: "POST",
data: { x: date }
});
PHP code in store.pro.php
if (isset($_POST['x'])) {
$raceDate = $_POST['x'];
echo($raceDate);
} else {
echo "no";
}
How do you know "it doesn't seem to be working" ?
add success method to your ajax, like this:
$.ajax({
url: "processes/store.pro.php",
type: "POST",
data: { x: date },
success: function(res) {
res = JSON.parse(res);
console.log(res);
}
});
Then, in store.pro.php put this:
if (isset($_POST['x'])) {
$raceDate = $_POST['x'];
echo json_encode($raceDate);
} else {
echo json_encode("no");
}
exit; // You may need remove this line, after you check, that ajax call is working
and check console in your browser

setInterval for jQuery for loop trouble

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

Passing the query count in javascript variable

See i have below Code in my javascript
var itemCount = 5, activeScroll = 0, countScroll = 0;
setInterval(function() {
if(countScroll == (itemCount - 2))
{
activeScroll = 0;
countScroll = 0;
$('#list').animate({scrollTop: 0});
}
else
{
activeScroll += 250;
countScroll += 1;
$('#list').animate({scrollTop: activeScroll});
}
}, 2000);
and my query string in php code is
$userads = mysql_query("SELECT * FROM user_ads ORDER BY `user_addate` DESC");
$adcount = mysql_num_rows($userads);
i am trying to assign value of $adcount in javascript variable var itemCount;
query is running in test.php and javascript is scroller.js.
Please help me .
You can output javascript by test.php:
<?php
$userads = mysql_query("SELECT * FROM user_ads ORDER BY `user_addate` DESC");
$adcount = mysql_num_rows($userads);
?>
<script type='text/javascript'>
var itemCount = <?php echo $adcount; ?>;
setupTimer(itemCount);
</script>
Make sure the scroller.js defines the function setupTimer(itemCount) that performs the task you want, instead of firing right away.
First you need to request the value from the server. Then you can assign it.
var itemCount;
setInterval(function() {
$.get('test.php', function(response) {
itemCount = response.itemCount;
// you scroll logic here
}, 'json');
}, 2000);
In test.php you should output the value by something like this:
$output = array(
"itemCount" => $adcount
);
print json_encode($output);
in scroller.js type this code:
$.ajax("test.php", {
type: 'post',
data: {
count:itemCount
},
sync: true,
success: function (adcount) {
itemCount=adcount;
}
});
in test.phptype this code:
if (isset($_POST['count']))
{
echo $adcount;
exit;
}
notice:you should use jquery file in your script for ajax

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

Populating javascript array with async geocode function

So, I'm parsing information and querying geocode with multiple addresses. I'm not entirely sure what's the best way of doing it. So here's what I'm trying to do.
for($j = 0; $j < $rawArray.length; $j++){
$baseStr = $addresNum != 'empty' ? $rawArray[$j][$addresNum] + ' ': '';
$baseStr += $addresStr != 'empty' ? $rawArray[$j][$addresStr] + ' ': '';
$baseStr += $addresDiv != 'empty' ? ', ' + $rawArray[$j][$addresDiv] : '';
$baseStr = ($baseStr.toLowerCase().indexOf("qc") >= 0 || $baseStr.toLowerCase().match(/qu[e-é]bec/) ? $baseStr : $baseStr + ", Qc");
console.log("Looking for: " + $baseStr.match(/\w\d\w([ ])*\d\w\d/i)[0]);
$baseStr = $baseStr.match(/\w\d\w([ ])*\d\w\d/i)[0];
$geocoder.geocode({
address: $baseStr
}, function(locResult, status) {
$arrayCoords[$j] = new Array();
if (status == google.maps.GeocoderStatus.OK) {
$arrayCoords[$j][0] = locResult[0].geometry.location.lat();
$arrayCoords[$j][1] = locResult[0].geometry.location.lng();
}else {
$arrayCoords[$j][0] = '';
$arrayCoords[$j][1] = '';
}
});
console.log("found: " + $arrayCoords[$j][0] + $arrayCoords[$j][1]);
}
Now, I figured that populating an array and working with it would be a good idea. So I did this:
$timeout = setInterval(function()
{
for($j = 0; $j < $rawArray.length; $j++){
console.log($globalGoogleArray[$j]);
}
if($globalGoogleArray.length == $rawArray.length)
{
console.log($globalGoogleArray);
//TODO: stopTimer();
}
}, 100);
And just before the console.log("found: " + $arrayCoords[$j][0] + $arrayCoords[$j][1]);
I added $globalGoogleArray[$j] = $arrayCoords[$j][0] + ", " + $arrayCoords[$j][1];
If I can get $globalGoogleArray populated with my values then I can stop the timer and trigger a function that will work with the content of the array. This may not be the the best way of doing it and I'm open to suggestions, still, I'm not ending with what I want. The timer is placed on top of the for and the console.log inside it only returns undefined, even tough the console.log in the for (this one: console.log("found: " + $arrayCoords[$j][0] + $arrayCoords[$j][1]);) does output what I expect it to output.
Can anyone enlighten me as to why I can't get the output of the geocode in my globalGoogleArray?
Keep track of the number of calls that are returned within your callback function. When the last one has returned, process your $arrayCorrds array.
var resultCount = 0; //counter for number of calls that have returned
for($j = 0; $j < $rawArray.length; $j++){
...
$geocoder.geocode({
address: $baseStr
}, function(locResult, status) {
$arrayCoords[$j] = new Array();
if (status == google.maps.GeocoderStatus.OK) {
$arrayCoords[$j][0] = locResult[0].geometry.location.lat();
$arrayCoords[$j][1] = locResult[0].geometry.location.lng();
}else {
$arrayCoords[$j][0] = '';
$arrayCoords[$j][1] = '';
}
resultCount++; //increment count
if(resultCount === ($rawArray.length - 1)) {
//the last result has been retrieved, do something with $arrayCoords here
}
});
}
So, finally knowledge struck me like a glass of cold water. I was just supposed to simulate a loop.
I ended up creating 2 functions that call each other. I also think thats this is how I'm supposed to tackle this kind of situations.
Function one is called by an external function with an empty string:
function collectCoords($fromGoogleStr){
//If being called with params, add them
if($fromGoogleStr)
$globalGoogleArray[($globalGoogleArray? $globalGoogleArray.length : 0)] = $fromGoogleStr;
//Generate address string here here\\
if ($tmpCounter < $fullArray.length - 1){
$tmpCounter++;
generateGoogleCoords($adressString);
}else{
//Do something with the complete answer
}
}
Once the address string is generated call the Google async function:
function generateGoogleCoords($baseStr){
$geocoder = new google.maps.Geocoder();
$arrayCoords = new Array();
$geocoder.geocode({
address: $baseStr
}, function(locResult, status) {
$arrayCoords[$j] = new Array();
$arrayCoords[$j][0] = locResult[0].geometry.location.lat();
$arrayCoords[$j][1] = locResult[0].geometry.location.lng();
collectCoords($arrayCoords[$j][0] + ", " +$arrayCoords[$j][1]);
});
}
So, the answer wasn't anything fancy. When Google answers the collect function is called again and the if in said function prevent all of this into going into a never ending loop.
GL&HF
Axel

Categories