Opening url retrieved with PHP inside Javascript - javascript

Need to open $link with javascript, that is retrieved from an XML file using PHP. Here's the code:
<?php
$url = "map.xml" ;
$xml = simplexml_load_file($url);
$link = $xml->url[mt_rand(0,count($xml->url)-1)]->loc ; // Get Random Location
?>
<html>
<head>
<title></title>
</head>
<body>
<script>
$(document).ready(function(){
window.open($link, "_blank"); // will open new tab on document ready
});
</script>
</body>
</html>

You cannot access php variables from javascript. With php you can render html and javascript on server. So you need to print your $link variable to the page:
window.open("<?= $link ?>", "_blank");
Note that short echo tag <?= is only guaranteed to be available on php 5.4+, if you are stuck supporting an older version use <?php echo instead

Related

Turn PHP variable into Javascript variable and use that Javascript variable as an argument in a Javascript function

An input from a form in my index.php page is sent to my search.php page. This input is turned into the PHP variable $q with $_GET. How do I turn this PHP variable into a Javascript variable that is a string? Then how do I pass this string as an argument in a Javascript function in the body tag when the page loads? The onload function only works if the first parameter is a string. Here is my simplified code:
<?php
if(isset($_GET["q"])) {
$q = $_GET["q"];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="assets/js/script.js">
var q = "<?php echo $q;?>";
</script>
</head>
<body onload="return Search(*PHP variable turned into Javascript string*, otherFunction(), otherFunction2())">
<div>
Content
</div>
</body>
</html>
Javascript within your script tag 'should' be ignored if there's a src for it. However you can't have precompiled php in a js file. One option is to set the javascript variables within your php files, then separately include your js files. If your js files make use of those variables, make sure to set the variables first:
<script type="text/javascript">
var q = "<?php echo $q;?>";
</script>
<script src="assets/js/script.js"></script>
The script doesn't work because you're trying to include an external JavaScript file, while also using the same tag for inline script.
This part
<script src="assets/js/script.js">
var q = "<?php echo $q;?>";
</script>
Should look something like this
<script src="assets/js/script.js"></script>
<script>
var q = "<?php echo $q;?>";
</script>
Fully fixed code
<?php
if(isset($_GET["q"])) {
$q = $_GET["q"];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="assets/js/script.js"></script>
<script>
var q = "<?php echo $q;?>";
</script>
</head>
<body onload="return Search(q, otherFunction(), otherFunction2())">
<div>
Content
</div>
</body>
</html>
Edit: Footnote
As #dossy points out, you should avoid directly passing user input into the HTML code. Use json_encode() to avoid any malicious code or invalid input.
<script>
var q = <?php echo json_encode($q); ?>;
</script>
This is what json_encode() is for. Other answers that use the naive approach of var x = "<?php echo $var; ?>"; will break if $var contains a double quote, for example.
This is the safest way of doing this:
<script type="text/javascript">
var q = <?php echo json_encode($q); ?>;
</script>

How to convert and transmit PHP Variable data Using JSON to HTML page's Javascript

I can't seem to figure it out how to convert the following PHP variable to HTML:
$persondata = "<div id='teach'><h3>Name: " . $row["fname"]. "<br>User Name: " . $row["username"]. "</h3><p>Password: " . $row["upass"]. "</p></div><br>";
I wanted to pass that exact data to my HTML page, so that I can use JavaScript's getElementById function to insert it into a selected data field.
I asked a similar question here, which helped me work out some of logic I need, but I can't work out this part of the equation.
If you could please let me know of a simple way of going about this, it would be very much appreciated, as I don't even know the keywords to search for.
Hope below code help you:
<?php
$persondata = '';
foreach($rows as $row){
$persondata .= "<div class='teach'><h3>Name: " . $row["fname"]. "<br>User Name: " . $row["username"]. "</h3><p>Password: " . $row["upass"]. "</p></div><br>";
}
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#data-row').html("<?php echo $persondata ?>");
});
</script>
</head>
<div id="data-row"></div>
A javaScriptVar equals with an echo in php of your php variable.
That is to put php inside js
<script type="text/javascript">
//Your JS
var jsvar = <?php echo $persondata; ?>
//Your JS
</script>
Put PHP var like above into js.
Continuing from above answer:
That is to put php inside js
<script type="text/javascript">
//Your JS
var jsvar = <?php echo $persondata; ?>;
//Your JS
</script>
Put PHP var like above into js.
If you want to transmit data from a PHP script in a server to a client side HTML page for using in js. Go like following.
First get all your data in PHP in an array and use json_encode() and after that echo that variable.
Now in the client side HTML use jQuery.ajax() and send request to that PHP file in server.
When you have the response in Json use js to fragment it and append
wherever you want.
Above is the basic procedure to send data from PHP to HTML page using JS.

how to convert javascript variable to php variable in the same file

I have file named test6.php having javascript variable i need to convert this variable to php variable but when i run it give me an e error (PHP Notice: Undefined index: variable in /Applications/MAMP/htdocs/test6.php on line 14)
<!doctype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var variableToSend = 'foo';
$.post('test6.php', {variable: variableToSend});
</script>
</head>
<body>
<?php
$x = $_POST['variable'];
echo $x;
?>
</body>
</html>
note that i have only one file (test6.php) containing javascript code and php code and i am trying to convert javascript variable to php variable in the same file and i need to use post not get or submit form
Why error
you should know the processing of a php file rendering from the server to the client , it is :
1. client request the page
2. PHP parser (in server) -> php 2 HTML -> send to client
2. web browser load HTML
3. JavaScript running ~
so you can't get variable of "variable" when you run your php file . Becuase Js has not been running ~ . you should print the value of php echo at JS after ajax .
how about change the JQuery code
$.post('test6.php', {variable: variableToSend});
to
$.post('test6.php', {variable: variableToSend} ,
function(returnValue){
console.log(returnValue) ;
});
I think it will be ok , but i am sorry i can't test it ~
Check to see if it is set before you output it
<?php
if( isset($_POST['variable']) ) {
$x = $_POST['variable'];
echo $x;
}
?>
But I do not think this is what you actually want. The Ajax call is not going to update the current view.
Bring the php section to the top and use isset($_POST['variable']) to check if the variable exist or not.
<?php
if( isset($_POST['variable']) ){
$x = $_POST['variable'];
echo $x;
return;
}
?>
<!doctype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var variableToSend = 'foo';
$.post('test6.php', {variable: variableToSend});
</script>
</head>
<body>
</body>
</html>

PHP javascript class variable value in php echo

this is simple example i want java script class variable to php echo please fix the following example to php echo value out put
<!DOCTYPE html>
<html>
<body>
<div class="example">The Book</div>
<? echo '<div class="example">The Book</div>'; ?>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
x[0].innerHTML = "Hello World!";
}
</script>
</body>
</html>
out put of java-script "The book" but php echo is '<div class="example">The Book</div>' Targeted out put of php The book
Javascript is run on the client, PHP is run on the server. If you want PHP to use the values calculated in javscript you first have to send it to the server, either through something like AJAX, or perhaps just a query string if you don't mind loading a new page or loading the same page again but with a query string appended to the URL.

Call php function on click of a button

I am trying to call a php function on click on a button using Javascript. It does not seem to be working fine.
Is there a better way to call php function on click of a button
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function executeShellScript(clicked)
{
var x="<?php ex(); ?>";
alert(x);
return false;
}
</script>
</head>
<body>
<input type="button" id="sample" value="click" onclick="executeShellScript()"/>
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
function ex(){
echo "Trying to run shell script from the web browser";
echo "<br>";
$contents = file_get_contents('/var/www/shellscriptphp/helloworld.sh');
echo shell_exec($contents);
$result = shell_exec('sh /var/www/shellscriptphp/helloworld.sh');
echo $result;
}
?>
</body>
</html>
You cannot invoke a php function just like the way you have explained above. Because php script executions happen before the source of the webpage is sent to the client browser from the server.
However you can do it via an ajax call in which you invoke a client side side js function onclick of the button and and that function inturn makes an ajax call to a server side page and returns the result back.
example:
Here is a sample code which you may refer. This page makes a POST ajax request to itself and gets the response back. Let me know incase of errors as i havent run it here.
<?php
/** this code handles the post ajax request**/
if(isset($_POST['getAjax'])) {
/* you can do this below settings via your php ini also. no relation with our stuff */
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
/* setting content type as json */
header('Content-Type: application/json');
$result = shell_exec('sh /var/www/shellscriptphp/helloworld.sh');
/* making json string with the result from shell script */
echo json_encode(array("result"=>$result));
/* and we are done and exit */
exit();
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.1.js" type="text/javascript"></script>
<script type="text/javascript">
function executeShellScript(clicked)
{
//$_SERVER["REQUEST_URI"] is used to refer to the current page as we have the ajax target as this same page
$.post('<?PHP echo $_SERVER["REQUEST_URI"]; ?>',{"getAjax":true}, function(data) {
alert(data['result']);
return false;
});
}
</script>
</head>
<body>
<input type="button" id="sample" value="click" onclick="executeShellScript()"/>
</body>
</html>

Categories