Updating PHP from JavaScript for loop - javascript

I currently have a JavaScript for loop which increments 'i'. I want to use this to increment a string within a PHP function call like so:
for (var i=1; i <= <?php echo $totalPages[0] ?>; i++){
if(selection=="page"+i){
<?php
$test = 'page'.+i;
?>
document.getElementById("commentid").value = "<?php query2($test,$_SESSION['courseID'], $_SESSION['userID']) ?>";
}
}
This function should call the function query2('page1,2,3,4...',$_SESSION['courseID'], $_SESSION['userID']) incrementing 'pagei'. Although i get the following error:
Uncaught SyntaxError: Unexpected token <

JavaScript is client-side, PHP is processed on the server side and will not be in the HTML output/the environment the JavaScript will run in. What you are attempting is simply not possible.

So you would like sth similar to:
var totalPages = <?php echo $totalPages[0] ?>
var comments = [''<?php
for($i=1;i<$totalPages[0];$i++)
echo(",'".query2("page".$i,$_SESSION['courseID'], $_SESSION['userID'])."'");
?>]
for (var i=1; i <= totalPages; i++) {
if(selection=="page"+i){
document.getElementById("commentid").value = comments[i];
}
}

Related

Javascript storing first value from foreach php function and keep repeating it

I have a javascript file that doing encoding for some string and implement it inside foreach PHP function to get values but unfortunately javascript holding and storing the first value from the foreach function only and keep repeating it
PHP
foreach ($json_content as $index => $array) {
echo '<textarea id="index" style="display:none">'.$index.'</textarea>';
echo '<textarea id="encoded'.$index.'" style="display:none">'.$aa_encode.'</textarea>';
echo '<script type="text/javascript" src="decdoe.js"></script>';
echo '<script type="text/javascript">function();</script>';
}
Javascript
var index = document.getElementById("index");
var AEncoded = document.getElementById("encoded"+index.value);
document.write(index.value);
document.write(function(AEncoded.value));
Output
000
firstvalue/firstvalue/firstvalue
What I missed?
Here is the solution
First: I added the ID inside a loop in the Javascript file like this
var i;
for (i = 0; i < $numberofloops ; i++) {
var AEncoded = document.getElementById("encoded"+[i]);
}
Then pulled out the function call from the foreach PHP
foreach ($json_content as $index => $array) {
rest of code here
}
echo '<script type="text/javascript">function();</script>';
if all you need to do is store every $index into a textarea and save it into a java var, then try throwing a while look on every case of echo that you need all variables from...
so for example, you would put a code like this:
while($index = value){
echo $index
}
inside of your #index textarea then grab that textarea's value with java

Incrementing Array Index on button click in Javascript

Below is my javascript code! I'm trying to increment the index of array $arr everytime the user clicks a button. The array is defined in a separate php tag! Where am I going wrong?
function option1() {
var i = 0;
document.getElementById("btn0").value = "newButtonValue";
document.getElementById("question").innerHTML =
"<?php echo $arr["results"][i++]["question"] ?>";
}
Where your compiler return output to browser your php code was compiled and you can't run it such as javascript.
you can use this js:
var arr = <?php echo json_encode($arr["results"]);?>;
function option1() {
var i = 0;
document.getElementById("btn0").value = "newButtonValue";
document.getElementById("question").innerHTML = arr[i++]["question"];
}
.html file
<button onclick="addIndex(this)" queNo="0">newButtonValue</button>
in .js file
function addIndex(btn) {
var i = btn.getAttribute("queNo")
console.log(i);
btn.setAttribute("queNo", i++);
document.getElementById("question").innerHTML = "<?php echo $arr['results']["+i+"]['question'] ?>";
}
Hope it's help you

Sending PHP array to Javascript

I have created an array in PHP. And I need to get that array into a javascript function. This is what I have tried.
$sql = "SELECT * FROM Questions WHERE Form_ID='$FormID' AND QuestionsDataHave='YES' ORDER BY Questions_ID+0, Questions_ID";
$GetTheValidationRule = mysqli_query($con, $sql);
$ValidatinArray = array();
$J = 0;
while($RowVal = mysqli_fetch_array($GetTheValidationRule)){
$ValidatinArray[$J] = $RowVal['Validation_Type'];
$J++;
}
And This is my javascript code.
$(document).ready(function() {
$("form").submit(function(){
var P= <?php echo json_encode($ValidatinArray); ?>;
var O = P.length;
alert(O);
return false;
});
});
But this gives me an error like this
SyntaxError: syntax error
var P= <br />
Isn't it possible to get the array in this way. Please someone help me.
UPDATE: This is the final out put of my error message
<script>
$(document).ready(function() {
$("form").submit(function(){
alert('AAAAAAAAAAAAAAAAAAA');
var IDsOfTheColumns = document.getElementsByName("DataColumnID[]");
var Data = document.getElementsByName("DataInputValue[]");
var A = IDsOfTheColumns.length;
alert(A);
<br />
<b>Notice</b>: Undefined variable: ValidatinArray in <b>C:\xampp\htdocs\PHIS\CreateTheForm.php</b> on line <b>16</b><br />
var P = null; return false;
});
});
</script>
Sorry for the late response...Try rewriting your document.ready as:
$(document).ready(function() {
$("form").submit(function(){
var P = JSON.parse('<?php echo json_encode($ValidatinArray); ?>');
var O = P.length;
alert(O);
return false;
});
});
The problem is, that in the variable $ValidatinArray is not available in the file, that prints the javascript code. Maybe this manual page helps you:
http://www.php.net/manual/en/language.variables.scope.php
Try this:
<?php
echo ' <script>
$(document).ready(function() {
$("form").submit(function(){
var P= '. json_encode($ValidatinArray) . ';
var O=P.length;
alert(O);
return false;
});
});
</script>';
?>
What you do is simply echo the js using php.
Your tag is coming from the form that you are submitting. check what your form data is before you encode it to verify the output. you can use console.log($("form));
Also using form is not a good idea since if you have more than one form and form is a global name. For forms you should give it a unique form name like "myForm" so that you can target that specific form.
Hope this helps
first of all I recommend that you verify that the variable $ValidatinArray exists and that it is being passed correctly to the file where you are doing the "echo".
the error you show indicates that from the beginning the variable that contains the array does not exist.
if the SQL query is inside a php function check that you are returning the variable.
example
<?php
function GetData(){
// ... here is the code to get the information from the database ...
return $ValidatinArray;
}
$ValidatinArray = GetData();
?>
once you have validated that this array exists we can now see the problem of passing the data to JavaScript:
It all depends on how the structure is, if you have the PHP code and the JavaScript function in the same file you can simply use this method inside the php fil:
// ... php file code
?>
<script>
$(document).ready(function() {
$("form").submit(function(){
// you can use any of the two methods that I leave you here
// Using only json_enconde
var P= <?= json_encode($ValidatinArray) ?>;
// Using json_enconde to pass the array as a string and using JSON.parse to have JavaScript convert it to an object
var P= JSON.parse('<?= json_encode($ValidatinArray) ?>');
var O = P.length;
alert(O);
return false;
});
});
</script>
In case the php file is executed at the moment of opening the page and the file that contains your function in JavaScript is in another file:
You can generate a "global" JavaScript variable from the php code as follows
// ... code php file
?>
<script>
window.variablename = <?= json_encode($ValidatinArray) ?>
</script>
<?php
inside your JS file you can receive the array like this
$(document).ready(function() {
$("form").submit(function(){
var P= window.variablename ;
var O = P.length;
alert(O);
return false;
});
});
PD: using <?= is equivalent to using echo
In php json_encode the array like this:
$inlinejs='';
$inlinejs.='var validatinArray=\''.addslashes(json_encode($ValidatinArray)).'\';'."\n";
$inlinejs.='var validatinArray=eval(\'(\' + validatinArray + \')\');'."\n";
and in javascript:
$(document).ready(function() {
$("form").submit(function(){
<?php echo $inlinejs; ?>
console.log(validatinArray);
});
});

How to bring PHP array value to Javascript?

<html>
<head>
<script language="javascript">
function validatefrm(){
for (var i= 0 ; i< 3 ; i++){
window.alert(i+window.document.contact[i].value);
}
return false; //to prevent form from submitting for debugging
}
</script>
</head>
<body>
<form name="editform" onsubmit="return validatefrm();" method="POST">
<?php
for($i=0; $i<3; $i++){
print "<input type='textbox' id='contact".$i."' value='".$i."'>";
}
?>
<input type="submit" value="Submit Values">
</form>
</body>
</html>
Hi, I'm new to php and javascript.
I'm trying to call the form with the value of 0,1,2 with javascript but it wont work. Unless i delete the for loop in javascript function and hard code it as Window.alert (window.document.contact0.value) and so on....Anyone can help? Must appreciate.
If I get your question correctly, you need to access the elements by ID. And the correct way is to use document.getElementById(...). In your case:
for (var i= 0 ; i< 3 ; i++){
window.alert(document.getElementById('contact' +i).value);
}
You are setting an ID for each element with php contact0, contact1 etc.
So in javascript look for that ID
function validatefrm(){
for (var i= 0 ; i< 3 ; i++){
window.alert(i+ ' '+ document.getElementById('contact'+i).value);
}
return false; //to prevent form from submitting for debugging
}
Your best choice would most likely be to use json_encode. This method outputs the array as a JSON array which can be assigned to a JavaScript variable in <script> tags. Associative arrays on the PHP side would get converted into JSON objects.
json_encode in the PHP documentation
<?php
$myArr = array(0, 1, 2);
?>
<!-- somewhere in the HTML document -->
<script>
var myArr = <?php echo json_encode($myArr); ?>;
// do something with myArr
console.log(myArr);
</script>
The php is executed on the server side, before it makes it to the browser. The javascript is executed on the client side, in the browser. You cannot pass php values to javascript like this.
You can make the php output javascript (in a script tag), and use that in your javascript code though.
<script>
var foo = [];
<?php
for($i=0; $i<3; $i++){
print "foo[".$i."] = ".$i;
}
?>
console.log(foo[0] + ", " + foo[1] + ", " + foo[2]);
<script>

Javascript loop create function and append value with PHP Query based id received

Below is my PHP MySQL Query and getting the last value result, I want to add 10 Javascript functions into my PHP page at end of page, however counting of variable works but I am not able to concat that value to function and other variable names.
Below is my code:
<script>
<?php
$brSql = "SELECT BRANCH_ID FROM `tb_um_client_branches` ORDER BY BRANCH_ID DESC LIMIT 1";
$brRset = mysql_query($brSql) or die('BRANCH LAST ID QUERY FAIL: '.mysql_error());
$brRID = mysql_fetch_row($brRset);
for($i = 0; $i < 10; $i++){
?>
cnter = (<?php echo $brRID[0]; ?> + <?php echo $i; ?>)
function getChecked_+cnter(){
var nodes+cnter = $('#tt_+cnter').tree('getChecked');
//var nodes = $('#tt').tree(data-options="method:'get',animate:true,checkbox:true");
var s_+cnter = '';
for(var i_+cnter=0; i_+cnter<nodes_+cnter.length; i_+cnter++){
if (s_+cnter != '') s_+cnter += ',';
s_+cnter += nodes_+cnter[i_+cnter].id + ' ' + nodes_+cnter[i_+cnter].text;
}
//$('#OLD_BRANCH_FILTERS_+cnter').value = s_+cnter;
$('#OLD_BRANCH_FILTERS_'+cnter).attr('value', s_+cnter);
//alert(s_+cnter);
}
console.log(cnter);
<?php
}
?>
</script>
Below is error, I am getting:
SyntaxError: missing ( before formal parameters
function getChecked_[cnter](){
Earliest help will be appreciated.
Thanks in advance !
This syntax
function getChecked_+cnter(){
is not valid.
You should use something of that
this["getChecked_"+cnter] = function() {
Important: there is a little difference with this declaration.

Categories