how to use javascript variable inside php in javascript function - javascript

I'm using JavaScript to redirect a page with dynamic parameter.
Here is the code, I had to use the PHP function inside JavaScript. It works but it isn't using the javascipt variable
<script type="text/javascript">
var $map = jQuery.noConflict();
$map(document).ready(function(){
$map("#map_search").click(function(){
var staffname = $map("#staffname").val();//alert(staffname);
var from = $map("#cdate_from").val();
var to = "<?php echo site_Encryption(from); ?>";alert(to);
var status = $map("#status").val();
window.location = "http://localhost/staff/booking.php?date="+to+"&tdate="+to;
var to = "<?php echo site_Encryption(from); ?>";alert(to);
Here I use the PHP function and "from" is JavaScript variable that I want to use.

You can do an ajax request, something like:
var from = blablah...;
$.getJSON("encryption.php", {from : from}, function (data)
{
alert(data.to);
});
encryption.php :
<?php
blabla...
echo json_encode(array("to" => site_Encryption($_GET["from"])));
?>
(It's a sample code, don't copy-paste, read some ajax tutorials ^^)
An alternative could be to make the encryption on client side.

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

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

how to use javascript variable in php inside a javascript function

i am trying to fetch JavaScript variable "i" in my PHP Code within a JavaScript function in the below code, I find problem in retrieving records, either first record or the last record repeats instead of all records in database.. can you guys help me out ?
Thanks
<?php
$query21 = $mysqli->query("SELECT * FROM register");
$nr = mysqli_num_rows($query21);
while ($row = mysqli_fetch_assoc($query21)) {
$results[] = $row;
}
?>
<script language="javascript" type="text/javascript">
var intervalID = 0;
var time = 10;
MsgPop.displaySmall = true;
MsgPop.position = "bottom-right";
$(document).ready(function(){
var test = MsgPop.open({
Type: "success",
AutoClose: true,
Content: "Welcome to MsgPop!"});
MsgPop.live();
});
function showMessages(){
var n = '<?php
echo $nr;
?>';
var i = 0;
while (i < n){
var name = '<?php
echo $results[i]['name'];
?>';
MsgPop.open({
Type: "success",
Content: name,
AutoClose: false});
i++;
}
</script>
First you have to create a php file which return same array. File contain
$query21 = $mysqli->query("SELECT * FROM register");
$nr = mysqli_num_rows($query21);
while ($row = mysqli_fetch_assoc($query21)) {
$results[] = $row;
}
echo json_encode($results);
exit;
Now you have to call this file using ajax from your javascript code.
$.ajax({
type: "POST",
url: "sql.php", //your file url
})
.done(function (data) {
//you get your array data(json format)
});
now you get that array in ajax response in json format and you can do anything with this data.
Impossible: PHP is a server side language that runs only at server. but javascript is a client side script it only run at your browser only. Php only gives response depends on your requests. The roll of php is end at server. But the javascript work with your response only, that is javascript can work at browser only.
You could try using AJAX, or else it isn't happening. Like said PHP is server-side only... Good luck!
PHP cannot fetch javascript variables. You should try another strategy.
At the server side (PHP), try to store $resuts in a javascript variable.
var results = '<?php echo json_encode($results); ?>';
Then at the browser side, try to access the data with javascript functions.
var name = results[i]['name'];

Passing array value from html to javascript

Note: using the Laravel framework but the concept shouldn't be too different.
How would I go about passing my $data['method'] and $data['id] to javascript?
<div id="player" data-method="{{ $data['method'] }}" data-id="{{ $data['id'] }}"></div>
Data method and Data id are passed through a controller.
In javascript I've currently got
var method = "<?php echo $data-id[]>";
var id = "<?php echo $data-method[]>";
Which obviously don't work
To get the method:
var method = document.getElementById("player").getAttribute("data-method");
And to get the id:
var id = document.getElementById("player").getAttribute("data-id");
In addition to #chris97ong answer, if you use jQuery, then you can use such constructions:
var method = $('#player').data('method');
var id = $('#player').data('id');
But if you want to paste id and method values directly to javascript, then use:
var method = "<?php echo $data['id']>";
var id = "<?php echo $data['method']>";
Exactly like in your own way.
Jeffrey Way provides a nice plugin to pass variables to JavaScript in your controller: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
You can pass array as
<?php
$array = array("a","b","c","d");
$json_str = json_encode($array);
?>
<a str='<?php echo $json_str; ?>' class="array_pass">Pass Value</a>
<script>
$(document).ready(function(e) {
$(".array_pass").click(function() {
var str = $(this).attr("str");
var array = jQuery.parseJSON(str);
alert(array[0]);
});
});
</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