call js function from php file [duplicate] - javascript

This question already has answers here:
How to call a JavaScript function from PHP?
(12 answers)
Closed 6 years ago.
I have a js file.
jiten.js
function myFunction(p1, p2) {
return p1 * p2;
};
I have to call this function from php file
Demo.php
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Mosquitto Websockets</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="jiten.js" type="text/javascript"></script>
</head>
<body>
<?php
echo '<script type="text/javascript">myFunction(2,4);</script>';
?>
</body>
</html>
But When I run this file, I get nothing....

PHP and JavaScript are different languages, they can be embedded but, each language has to call its own functions.
You are returning value through JavaScript code, but, you can not echo it with PHP and not printing it through JavaScript.
You need to print the value by using document.write() in JavaScript.
Corrected Code:
<script type="text/javascript">
function myFunction(p1, p2) {
return p1 * p2;
};
</script>
<?php
echo '<script type="text/javascript">document.write(myFunction(2,4));</script>';
?>
Output:
8

Your code is working well, but your Javascript function doesn't display anything, it just returns a value.
You should use something like console.log() or alert() to display the result.

Try This
echo '<script type="text/javascript">document.write(myFunction(2,4));

Related

How to assign JavaScript variable to PHP session variable?

Here's javascript code that i have
var randomnum = 30;
and here's PHP code
<?php $_SESSION['numbertoguess'] = '<script>document.write(randomnum)</script>';?>
But this is not passing the value
But when i am trying this code below, it works. It gives session variable that the value 'a sample thing'.
<?php $_SESSION['numbertoguess'] = 'a sample thing';?>
Look at the following code. The PHP session is assigned to 30 from the Javascript value. however am not sure if this is good way for implementation.
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Html Page Title</title>
</head>
<body>
<script>
var randomnum = 30;
</script>
<?php $_SESSION['numbertoguess'] = '<script>document.write(randomnum)</script>';?>
<?php echo $_SESSION['numbertoguess']; ?>
</body>
</html>
You can't access Session directly in JavaScript.
You can make a hidden field and pass it to your page and then use JavaScript to retrieve the object via document.getElementById

How to excecute a <p:remoteCommand> from javascript

I have a trouble when I try to excecute a remote command from a javascript code, always in the console I have the erro, ReferenceError: notificar is not defined and I don’t know why, this is my code, thanks
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
Hello from Facelets
<p:growl id="notifyGrowl" widgetVar="notifyGrowl" life="3000" showDetail="true"/>
<h:form>
<p:remoteCommand name="notificar" actionListener="#{remoteCommandView.execute}" update="notifyGrowl" />
</h:form>
</h:body>
<script type="text/javascript">
if (window.WebSocket) {
var ws = new WebSocket("ws://localhost:8080/SEIPA3/push");
} else {
console.log(" Browser doesn't support it");
}
ws.onmessage = function (event) {
notificar();
};
</script>
Guys I solved this problem, what happened was that I ran my application and as I was in the browser, I went to my client directly from the url by typing the address where he is staying, doing an inspection of the source code of the page of the cliene I realize that I was still showing the code of primefaces as such, which is not right, should have been processed and displayed as pure html, so put a button from my index to send me to the client, so that now when doing the inspection showed me the html code already processed, and everything went well. thanks.

Cant echo PHP variable inside <script> tags? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
This is my PHP code. I want error to be displayed using an alert window.
if ($projectid=="")
{
$error = 'You must choose a project.
Click ‘back’ and try again.';
include error.html.php';
exit();
}
This is error.html.php that is supposed to be parsed by the browser
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Script Error</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script>
var error = <?php echo $error ; ?>;
window.onload = function(){ alert(error); }
</script>
</body>
</html>
Wahts up with the script tags ? Do they prevent PHP from running ?
The real problem is that this is what your rendered result looks like:
var error = You must choose a project.
Click ‘back’ and try again.
Does that looks like valid JavaScript to you? I think not.
var error = <?=json_encode($error);?>;
That should result in:
var error = "You must choose a project.\r\n Click ‘back’ and try again.";
Much better.
Your problem is that javascript is run on the client and will run after the page loads and so after the php is run on the server.
However, you can do something like the following which allows php to set the value of a javascript variable when the page loads and then AFTER the page is loaded runs the javascript to display the message.
<?php
$error = "test me";
echo "<script>error = '" . $error . "'</script>";
?>
<script>
var error;
window.onload = function(){
alert(error);
}
</script>
UPDATE
Based on your edits, here's an updated answer.
The echo "<script>error = '" . $error . "'</script>" is needed to assign the $error to the javascript variable when the page is loaded.
if ($projectid=="")
{
$error = 'You must choose a project.
Click ‘back’ and try again.';
echo "<script>error = '" . json_encode($error) . "'</script>"
include error.html.php';
exit();
}
And the html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Script Error</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script>
var error;
window.onload = function(){ alert(error); }
</script>
</body>
</html>
If you have an $error within your PHP, then you can write:
<?php
echo "<html><head></head><body></body>";
$error = "whoops!"; // just for testing
echo "<script>\n";
echo "alert('{$error}')\n";
echo "</script>\n";
echo "</html>";
?>
and the alert will happen as soon as the page is loaded, tested it on my server. This is for the situation where the $error is happening on the server side. (By the way, thanks for the fun question this late in my day!)
Actually it's quite simple.
if ($projectid=="")
{
$error = 'You must choose a project.
Click ‘back’ and try again.';
include 'error.html.php';
exit();
}
$error will now contain You must choose a project. Click ‘Back’ and try again. Note, there are no quotes, so then the line
var error = <?php echo $error ; ?>;
looks like this in the client:
var error = You must choose a project.
Click ‘Back’ and try again;
Which naturally causes an error as that is not valid javascript. You need to add quotes, either inside the definition of $error serverside or outside the PHP -- something along the lines of:
$error = '"You must choose a project.
Click ‘back’ and try again."';
OR
var error = '<?php echo $error ; ?>';
as per your preference...
You certainly can use inline php to generate javascript code. They will, of course, be executed in different contexts, Server-Side vs. Client-Side, but that's mostly irrelevant.
However, you have to realize that the two languages aren't communicating as such, but part of the JS is being generated by the output of the PHP. You have to be careful about that output. One of the issues you have is that JS does not support multiline strings, so the value of $error in PHP can't have a newline.
Try this instead:
if ($projectid=="")
{
$error = 'You must choose a project. Click \"back\" and try again.';
include 'error.html.php';
exit();
}
and
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Script Error</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<script>
var error = "<?php echo $error ; ?>";
window.onload = function(){ alert(error); }
</script>
</body>
</html>
List of fixes:
Fixed quotes in the include statement.
Added quotes around the inline PHP echo in the JS code.
Removed the newline in the $error var so JS gets it all in one line.
Removed html quotes and replaced them with escaped regular quotes. Alert boxes don't process those.

Sending a JSON encoded PHP variable to JS

I am trying to send a PHP variable to my javascript. In order to do this, I encode the php variable with json, send it to my view with my controller, use it as a value in a hidden html form, and then pull the value with js, using parseJSON to get the final product.
HTML (I'm using laravel, the brackets are equivalent to php tags):
<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="{{$artist_likes}}">
JS
var artist_likes = $('#js-helper-artist-likes').val();
console.log(artist_likes);
In the page source, I see that the value is populating with the json string, but when I print it to the console from my js like the above, all that is showing is: [{
I am not sure why this is.
I want to perform:
var artist_likes_decoded = $.parseJSON(artist_likes);
to get the decoded variable in JS, but this is impossible without the encoded string coming up correctly in the artist_likes variable in js.
Any ideas what I'm doing wrong? Thank you.
<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="{{ echo $artist_likes}}">
You could use:
<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value="<?= json_encode($artist_likes) ?>">
<?php
$yourVariable ="something";
$arr = json_encode(array("name"=>$yourVariable));
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<input type="hidden" id="js-helper-artist-likes" name="js-helper-artist-likes" value='<?php echo $arr; ?>'>
<script>
$(document).ready(function(){
var artist_likes = $('#js-helper-artist-likes').val();
console.log($.parseJSON(artist_likes));
});
</script>
</body>
</html>

Error message in Javascript

I have a PHP code:
if($billing_total>$limit_to_send){
echo '<script type="text/javascript">
window.onload = function() {
alert("Sorry, you do not have enough credit");
}
</script>';
When I am printing this message, it is being printed at the beginning of the PHP page as below:
<script type="text/javascript">
window.onload = function() {
alert("Sorry, you do not have enough credit");
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
-----------------------------------------------------------
This caused the header (logo) of my page in the browser to move down one line.
and the page will look very bad because all the items there will be moved down one line.
I hope it is clear to you. Please any solution ?
===========================================================================
Thanks for All ...
Solution:
$alert_message=<script type="text/javascript">
window.onload = function() {
alert("Sorry, you do not have enough credit");
}
</script>
Printing $alert_message somewhere in the HTML code before the body tag ^_^
Make sure you never output anything before the DTD (doctype declaration).
See this question for more information...
The doctype declaration must be the first element of your html page, it's from what the browser decides how to handle the rest of the html code. Outputting anything before that will probably put your browser in quirks mode so you can't be sure how the browser will render your page.
How to avoid this?
The echo command gets executed as its line is reached, and it seems that the rest of your html code follows after that.
You could either
move the html DTD and header to the top of your php (but sometimes that is not possible) OR
store the error html in a variable, so instead of echo '<script ... do $errorhtml = '<script ... and output that string, if not empty, at a specific place in the head or body generating code of your php.
If you have no control over the original source, you could consider redirecting to an error page with its own html DTD, header and body which you can design as fits you best.
Either append die() into the if codeblock or have your php print the script somewhere in the body or head.
This shows a bad design of your application. I would suggest you change it to something like:
$errors = array();
if($billing_total>$limit_to_send){
$errors[] = 'Sorry, you do not have enough credit';
}
Then on your HTML file, before the <body> tag closes, read your array and display any errors
<?php if(is_array($errors)): ?>
<script type="text/javascript">
<?php foreach($errors as $error): ?>
alert('<?php echo $error; ?>');
<?php endforeach; ?>
</script>
<?php endif; ?>

Categories

Resources