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
Related
Hiii Everyone,
<script src="../../record/recordmp3.js?id=<?php echo $_GET['id'];?>&&test_no=<?php echo $_GET['test_no'];?>"></script>
<script type="text/javascript" data-my_var_1="some_val_1" data-my_var_2="some_val_2" src="/js/somefile.js"></script>
And I tried to get that passing value in recordmp3.js is
var student_id = this_js_script.attr('data-my_var_1');
var test_no = this_js_script.attr('data-my_var_2');
And also by
var student_id = "<?php echo $_GET['id'];?>";
var test_no = "<?php echo $_GET['test_no'];?>";
And my value is not passing correctly.Instead only '0' is passing In my index page I have some PHP variable value I need to pass that value to recordmp3.js file.Please help me to solve this issue.Thank you so much in advance.
I tried like below its working fine
<script src="../../record/recordmp3.js"></script>
<script type="text/javascript">
MYLIBRARY.init(["<?php echo $id; ?>", "<?php echo $test_no; ?>"]);
MYLIBRARY.helloWorld();
</script>
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // private
return {
init : function(Args) {
_args = Args;
// some other initialising
},
helloWorld : function() {
window.id= _args[0];
window.test_no= _args[1];
}
};
}());
You need to convert these values to json array. You cannot directly assign the php values to JavaScript variables.
Hope this answer is useful. Please let me know if you find any difficulties on converting to json value.
.js files don't execute and compile the php files,so in order to access the php variables in javascript the file should be .php.
script.php
<?php
$foo = 'Hello cool';
?>
<script>
var foo ='<?php echo $foo ?>';
console.log(foo);
</script>
i hope this example will solve your issue
I am trying to work out how to get thye last part of a url on click of a button dynamically from a pre populated csv file.
For example on click of <a href="mysite.com/" >button</a>
would grab a code from a CSV file (or something better) and the link would be mysite.com/code1.
However each code from the CSV will only be used once and be removed after
So first click = mysite.com/code1
Second click = mysite.com/code2
and so on getting code1 and code2 from the CSV file and never to be gotten again.
I can use either JavaScript or PHP, either is good, I'm just not sure on the syntax.
Like this:
<?php
$first = true;
$links = "";
$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
if (!$first) $links.=",";
$first=false;
//$line is an array of the csv elements
$links.='"'.$line.'"';
}
fclose($file);
?>
Plain JS
<script>
var links = [<?php echo $links ?>];
cnt = 0;
window.onload=function() {
document.getElementById("csvLink").onclick=function() {
window.open(this.href+links[cnt],"_blank"); // otherwise you need cookies
return false;
cnt++;
}
}
</script>
jQuery using Ajax:
<script>
var links = [<?php echo $links ?>];
cnt = 0;
$(function() {
$("#csvLink").on("click",function(e) {
e.preventDefault();
$("#someContainer").load(this.href+links[cnt]);
cnt++;
});
});
</script>
I want to assign some php to a javascript variable like:
var goldPrice = <?php echo ResourceArray::$goldLevel[$user->getResource($data->id, "goldLevel")]?>;
but ends up with: 1 (instead of 2000).
Here's my troubleshooting:
I have an array in a php class:
<?php
class ResourceArray {
public static $goldLevel = array(
0, 2000, 10000
),
I've tried to assign through a couple of variables to find the problem with no luck:
var goldLevel = <?php $user->getResource($data -> id, "goldLevel") ?>;
var goldPrice = <?php echo ResourceArray::$goldLevel[$user->getResource($data->id, "goldLevel")]?>;
var goldPrice1 = <?php echo ResourceArray::$goldLevel[1]?>;
This writes:
var goldLevel = 1;
var goldPrice = 1;
var goldPrice1 = 2000;
Finally I tried to assign a php variable to put in:
PHP: $goldLevel1 = $user->getResource($data->id, "goldLevel");
$goldLevel2 = 1;
js: var goldPrice2 = <?php echo ResourceArray::$goldLevel[$goldLevel1]?>;
var goldPrice3 = <?php echo ResourceArray::$goldLevel[$goldLevel2]?>;
This ends up like:
var goldPrice2 = ;
var goldPrice3 = 2000;
When I echo $goldLevel1 and $goldLevel2, it shows 1 and 1.
Trying this works fine with me:
<html><body>
<?php
class ResourceArray {
public static $goldLevel = array(
0, 2000, 10000
);
}
// set gold price to second entry of goldLevel array
$goldPrice = ResourceArray::$goldLevel[1];
// check to make sure we have a valid number
if (!is_numeric($goldPrice) || $goldPrice < 1)
$goldPrice = 0;
// this outputs 2000
echo $goldPrice;
?>
<script>
var goldPrice = <?php echo $goldPrice; ?>;
alert(goldPrice);
</script>
</body></html>
Try using json_encode()
Documentation for json_encode
Use it like this
var goldPrice = <?php echo json_encode(array(0, 2000, 10000))?>;
Just replace the array for the dynamically created one.
First of all create a variable of json
var jsonO = <?php echo json_encode(array(0, 2000, 10000))?>;
this will be a json string, convert it to javascript array
var goldPrice = $.map(jsonO, function(el) { return el; })
then use goldPrice array.
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];
}
}
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);
});
});