Php javascript - get page title in php variable - javascript

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

Related

use var from function.php file into scripts.js file

I have a function.php code simple one:
$var = "7000";
and I have another file script.js:
var Price = <?php echo $var ?>;
now it works when this code in the same file.
but when I separate the files its doesn't.
any suggestions?
As pointed out by GrumpyCrouton in his comment to you, variables out of one file can be read in another by including them
<?php
include('file1.php'); // include the file where the variable is defined
<script>
var Price = <?= json_encode($var) ?>; // in javascript code export the variable to js usign json
</script>
It is always safe to use json_encode and dump the variable directly into js no need to encapsulate it any more then that, I would add a semicolon at the end but that is more of a personal preference in this day and age.
Create a script called price.php with the following content:
<?php
header("Content-type: text/javascript"); // As suggested by Mark Eriksson
$var = "7000";
?>
const PRICE = <?php echo $var; ?>;
Now you can reference this JavaScript block on any HTML page:
<script src="price.php"></script>
You will have a global JavaScript variable (constant) called PRICE.
Do you need variable prices? No problem, you can pass a value as a parameter, for example:
<script src="price.php?price=8500"></script>
And in your price.php, you change it to:
<?php
$var = $_GET["price"];
?>
const PRICE = <?php echo $var; ?>;
Your HTML page still gets a constant named PRICE.
Well, if you want to access some PHP variables, then you need to use AJAX.
Its quite simple.
Do this inside function.php file
<?php
$var = "7000";
// Put your price into array to form it into JSON format further
$data = ["price" => $var];
return json_encode($data);
And following in your JS file.
let xhr = new XmlHttpRequest();
xhr.open('get', 'function.php', true);
xhr.onload = function() {
if (this.status == 200) {
var data = JSON.parse(this.response);
// Your final result
var Price = data.price;
}
}
xhr.send();

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

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.

How do i make my php variable accessible?

I am trying to implement a timer. I learned this idea from a SO post.
<?php
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
}
?>
This is my php code. My php,html and JS codes are in the same page. I have a button in my html. When a user clicks on the html page, It will call a Ajax function
//url:"onlinetest.php",
//dataType: 'json',
beforeSend: function()
{
$(".startMyTest").off('click');
setCountDown();
}
It will call setCountDown() method, which contains a line at the very beginning
var days = <?php echo $remainingDay; ?>;
When i run the page, it says[even before clicking the button] "expected expression, got '<'" in the above line. My doubt is
Why this php variable get replaced before i am triggering the button. Please let me know hoe to solve this or how to change my idea.
The problem is, since initial load, $_POST values aren't populated (empty on first load),
That variable you set is undefined, just make sure you initialize that variable fist.
<?php
// initialize
$remainingDay = 1;
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
echo json_encode(array('remaining_day' => $remainingDay);
exit;
}
?>
<script>
var days = <?php echo $remainingDay; ?>;
$('.your_button').on('click', function(){
$.ajax({
url: 'something.php',
dataType: 'JSON',
type: 'POST',
beforeSend: function() {
// whatever processes you need
},
success: function(response) {
alert(response.remaining_day);
}
});
});
</script>
That is just the basic idea, I just added other codes for that particular example, just add/change the rest of your logic thats needed on your side.
You can pass a php variable into JS code like
var jsvariable ="<?php echo $phpvariable ?>";
NOTE:
If you ever wanted to pass a php's json_encoded value to JS, you can do
var jsonVariable = <?php echo $json_encoded_value ?>; //Note that there is no need for quotes here
Try this,
var days = "<?php echo $remainingDay; ?>";

how to use javascript variable inside php in javascript function

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.

Categories