Passing my PHP variable value to Js file - javascript

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

Related

Php javascript - get page title in php variable

I just want to pass page title inside script using php.
val = document.title;
like below code.
<script>
"Val" : echo $val;"
</script>
You can assign php variables to js using following script.
<script>
var val= <?php echo $val; ?>
</script>
var title = (document.title);
console.log(title);
or
var title = $(document).find("title").text();
console.log(title);
Here is the code to get the title and set a new title :
test();
function test() {
var pgtitle=document.title;
console.log(pgtitle);
var pgtitle='test';
document.title = pgtitle;
};
Assign PHP variable to js
you just need to wrap code inside php tags
and file containing this code must be a valid php file eg. .php
this will not working inside .js file
<script>
var Val = '<?php echo $val ?>';
</script>
Assign js variable to PHP
you can make call to php file using ajax/jquery.ajax
$.ajax({
url: "yourphp.php",
method: 'post',
data: {'page_title': document.title},
success: function(resp){
//do something
}
});
in your php file
<?php
$title = $_POST['page_title'];
?>

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];

Problems in passing PHP array to JavaScript

I understand that the format for passing a PHP array to Javascript is:
<script type="text/javascript">
var obj = <?php echo json_encode($php_variable); ?>;
</script>
I have a php function that stores some values in a longitude and latitude array. These array do hold the right values within php since print_r() within php shows me that the array is correct.
print_r($latitude_array);
print_r($longitude_array);
Now, I pass on this array to JS in this manner:
<script>
var lati_array = "<?php echo json_encode($latitude_array); ?>";
var longi_array = "<?php echo json_encode($longitude_array); ?>";
alert(lati_array[0]);
</script>
In the beginning, when I open the HTML file, it shows me an empty array (which is expected because the PHP arrays aren't filled yet). Then user enters something, the php arrays are filled up with longitudes and latitudes. These values should now be passed to JS. However, it doesn't alert anything after that. I can't be sure if array is successfully passed to JS. What am I missing?
Try this:
<script>
var data = <?php echo json_encode( $data ); ?>;
</script>
Try like below:
<?php
$array_var = array(111, 222, 333, 444);
?>
<script>
var array_var = "<?php echo json_encode($array_var); ?>";
console.log(array_var);
array_var = JSON.parse(array_var);
console.log(array_var);
alert(array_var[0]);
</script>
You are getting a string in lati_array , Try to convert it into json like this:
<script>
var lati_array = "<?php echo !empty($latitude_array) ? json_encode($latitude_array) : ''; ?>";
var longi_array = "<?php echo !empty($longitude_array) ? json_encode($longitude_array) : ''; ?>";
lati_array = JSON.parse(lati_array);
alert(lati_array[0]);
</script>

Uncaught ReferenceError: testString is not defined

This is really weird..
I need to send a couple of variables through to jquery from PHP.. one is an INT and the other a string.
When $a is an INT it works fine but when i use a string, i get this error.. Uncaught ReferenceError: testString is not defined
Here is my code.
<?php $a = 'testString'; ?>
<script type="text/javascript">
var a = <?php echo $a; ?>;
alert(a);
</script>
I assumed that i needed to stick a (int) or (string) before the variable, but i wasn't entirely sure how to and unsuccessful in my googles/attempts.
Any ideas?
You forgot the quotes to make the value of var a a string:
var a = "<?php echo $a; ?>";
What you're writing into the document is:
var a = testString;
so javascript is looking for a variable called testString. Instead, you want the result to be:
var a = "testString";
so make sure you include the quotes around what php is writing in.
There are quotes missing in javascript code:
<script type="text/javascript">
var a = '<?php echo $a; ?>';
alert(a);
</script>

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