Why I cannot send php variable to javascript variable using jQuery? - javascript

I have javascript function using javascript variable from php variable using jQuery. The code is shown below:
jQuery:
$(document).ready(function(){
var v1 = <?php echo json_encode($v1,JSON_NUMERIC_CHECK); ?>;
});
javascript function
function abc(){
alert(v1);
}
I cannot print out the value of v1, but when I do not use jquery to send php variable to javascript variable, I use the below code after $v1 in php
<script type="text/javascript">
var v1 = <?php echo json_encode($v1,JSON_NUMERIC_CHECK); ?>;
</script>
And the function can print out value of v1.
But, I want to see which variables I have already used and see them at the top instead of at the bottom. So, I decide to use jquery but it fails. Where does it go wrong?
the second way which works for me is shown below:
<!DOCTYPE html>
<html>
<head>
<script>
function abc(){
alert(v1);
}
</script>
</head>
<body>
<?php
$sql = "SELECT r_ID,r_cname,address FROM rest ORDER BY count2+count3 DESC";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_array()){
array_push($name,$row["r_cname"]);
}
}
?>
<script>
var v1 = <?php echo json_encode($name); ?>;
</script>
</body>
</html>
Why there are no encapsulation problems?

Your alert(v1) needs to be inside the same function the var v1 = ... is in. And the JSON needs to be valid to print out a valid object.
A PHP printed variable often need not to be in jQuery. It almost certainly not need to be inside a jQuery function, trust me, because it is often just a piece of data.
I always use this method/practice:
<?php
//My businesses
?>
<!DOCTYPE html>
<html>
...
<head>
<script>
//By the way, HTML5 don't require you to state the type of script, it is defaulted to JavaScript.
var x = <?php echo json_encode($x, JSON_UNESCAPED_UNICODE);?>
</script>
<script>
//Rest of my code
$(function(){
//My jQuery here
})
</script>
</head>
<body>
...
</body>
</html>
Why declaring the variable inside jQuery "doesn't" work
It does, but outside the scope of $(function(){}), no one can access variables defined inside. It is a basic mechanism of JS. On the other hand, the function(){} inside $() is an argument, that is the second reason it doesn't work getting the value outside.
Example:
var a = 3;
function(){
var b = 4;
a; //<-- 3
};
b; //<-- undefined
Why the second script worked
Let's assume your code looks like this:
...
<script>
var v1 = <?php echo json_encode($v1, JSON_UNESCAPED_UNICODE);?>
</script>
...
<script>
$(function(){
v1; //There is a value
})
</script>
...
Because your new v1 variable is defined just under <script>, it is a global variable. A global variable can be accessed anywhere on the webpage.
In contrast, a local variable cannot be accessed outside the scope it is in. Look at this tree diagram:
window
|- v1
`- function x
|- v2
`- function y
`- v3
Basically, a variable can only be accessed by its children and never its parents. So:
v1 can be accessed inside inside and outside of function x and function y but v2 can only be accessed inside of function x and function y and v3 can only be accessed inside function y
Here is a table of what variables can be accessed where:
globally | function x | function y
------------|------------|-----------
v1 ✓ | ✓ | ✓
------------|------------------------
v2 | ✓ | ✓
------------|------------------------
v3 | | ✓
Final answer
You just need to do this: <script>var v1 = <?php echo json_encode($v1);?></script> before you use the variable on your webpage.

Your issue lays in timing and/or scope.
This code will run after the page is done loading and all the variables declared in it are encapsulated and exist only within it:
$(document).ready(function(){...})
Try this:
// Declaring variable in global scope.
var v1 = <?php echo json_encode($v1,JSON_NUMERIC_CHECK); ?>;
$(document).ready(function(){
// Open console to view result
console.log(v1);
});

Its working, follow the sequence
<?php
$v1 = ["a","b","c"];
?>
<script type="text/javascript">
v1 = <?php echo json_encode($v1,JSON_NUMERIC_CHECK); ?>;
abc();
function abc(){
alert(v1);
}
</script>
------------------- Updated code if js is before php code ----------------------
<script type="text/javascript">
$( document ).ready(function() {
v1 = $("#v1").val();
abc();
function abc(){
alert(v1);
}
});
</script>
<?php
$v1 = ["a"=>"aa","b"=>"bb","c"=>"cc"];
$v1_json = json_encode($v1,JSON_NUMERIC_CHECK);
?>
<input type="hidden" value='<?php echo $v1_json; ?>' id="v1">

Related

Passing my PHP variable value to Js file

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

Expression expected in PhpStorm when using php variables in JavaScript functions

When I am using changing php variables to JavaScript variables, I am getting "expression expected" error from PhpStorm.
I cannot change the extension of the file to something.js.php because I am already using blade template so it should be blade.php
<!DOCTYPE html>
<html>
<body>
<?php $myVar = 5;?>
<script type="text/javascript">
var myJavascriptVar = <?php echo $myVar; ?>;
var myJavascriptSecondVar = {{$myVar;}};
alert(myJavascriptVar + myJavascriptSecondVar);
</script>
</body>
</html>
I have added a sample html page for more clarification. In PhpStrom the
var myJavascriptVar = <?php echo $myVar; ?>;
and
var myJavascriptSecondVar = {{$myVar;}};
statements gives expression expected error.
That's a bug (incomplete inter-language handling) in PhpStorm.
https://youtrack.jetbrains.com/issue/WI-24968
https://youtrack.jetbrains.com/issue/WI-25739
possibly some another (from "Related" list) as well
Watch those tickets (star/vote/comment) to get notified on any progress. Right now they are not assigned to any specific future versions.
Here are two workarounds:
1. function
function blade(_)
{
return _;
}
var data = blade({{ $data }});
// or ES6 arrow function
var data = (_ => _)({{ $data }});
2. array
var data = [{{ $data }}].pop();
// or
var data = [{{ $data }}][0];

PHP to Javascript passing variable returns null results

Here is the code that I have:
https://jsfiddle.net/a6kukf3n/
The PHP variable $weekParses contains the following data:
WK 14,WK 15,WK 16,WK 17,WK 18,WK 19,WK 20,WK 21,WK 22,WK 23,WK 24,WK 25,WK 26,WK 27,WK 28,WK 29,WK 30,WK 31,
However, when I add it to the var weekCases on Javascript and try to print it to the console or my charts.js file it returns null, 1, 2 ,3 ,4 etc
What am I doing wrong? How do I send my PHP variable to JS?
Please create a new array in php and assign the value to array
$data_week=array();
while ($weeks = mysqli_fetch_row($numRowsQuery))
{
$data_week[]=$weeks
}
After that please try
<script type="text/javascript">
//pass php variable to js for open cases pw
<?php $weekParse = $data_week; ?>
var weekCases = <?php echo json_encode($weekParse); ?>;
</script>
Prepare PHP variable inside the PHP code and not in script tag
so in your PHP code write
$weekParse = json_encode($weeks);
And your script
<script type="text/javascript">
//pass php variable to js for open cases pw
var weekCases = '<?php echo $weekParse; ?>';
</script>
Hope this helps you.

jquery + php - Call Function From Another Javascript Wrapper

How could I call function in different jQuery wrapper like this:
<?php
if($trigger != ""){
?>
<script type="text/javascript">
jQuery(document).ready(function($){
var delay = 5000;
setTimeout(rmv, delay); // call the function here
});
</script>
<?php
}
if($triggered != ""){
?>
<script type="text/javascript">
jQuery(document).ready(function($){
function rmv(){ // function to be called
$(".adt_front_wrapper<?php echo $id; ?>").remove();
}
});
</script>
<?php
}
?>
I am trying to call a function which should be separated from the caller like the rmv function in the example code above. How could it be done?
You would need to put that function into a higher (shared) scope. For this example, you could use the window object itself.
window.rmv = function() {
$(".adt_front_wrapper<?php echo $id; ?>").remove();
};
In order to make that work, the declaration and definition of rmv needs to happen beforehand of course.

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);
});
});

Categories