Echo a php output within a Javascript code - javascript

I couldn't get the code below to display the success word, any idea what's the problem with the code below?
Thanks in advance.
<script type="text/javascript">
function verification(){
var s = document.test_form.textfield.value;
if (s == "") {
alert("Please enter a value");
return false;
} else {
<?php echo "sucess"; ?>
}
}
</script>

You need to wrap your echo in an alert
alert("<?php echo 'sucess'; ?>")

Your output in javascript is:
else {
sucess
}
What this mean? Try something like this if you want to force output by PHP:
else {
<?php echo "alert('success');"; ?>
}
Or just return true to confirm submitting the form:
else {
return true;
}

You can do 2 things:
console.log("<?php echo 'success'; ?>"); // Will display a message into JS console
or:
alert("<?php echo 'success'; ?>"); // Will display a message into JS alert box
In your code, you only writing 'success' inside the javascript code, and when the browser will try to execute this JS code, it will not understand 'success'and it will throw an error.

If you want to display the text on your page, you can use inside a document.write:
document.write("<?php echo "success"; ?>");
Otherwise, you can use an alert() or console.log()

document.getElementById('body').innerHTML('<?php echo 'sucess'; ?>');
assuming that your body tag has the id body(<body id="body">)
EDIT. of course you can do that with every tag that has an id.

If you are getting PHP to write Javascript you might want to think about using a templating engine like Smarty or Twig.

For the case the file is a Javascript
If the original file is an external .js (not a .php) and is being read on the client side (browser) then it simply does not know how to parse PHP.
Therefore when the browser gets to:
} else {
<?php echo "sucess"; ?>
}
It simply does not recognize the <?php and thus is throwing an error.
Replace the PHP string by alert("success") or, if you do want to query the server and have the server output something take a look into Ajax.
For the case the file is a PHP and the Javascript code is embedded in the html
Replace the code by
} else {
<?php echo 'alert("sucess";)' ?>
}

Related

How do I insert # character in echo statement for JavaScript?

When I include the # glyph in my statement, to return to an anchor on the page, the PHP code fails.
I've tried everything I can think of to resolve this issue, escaping PHP characters, writing JavaScript functions and the list goes on.
if (isset($_POST['name'])) {
$_POST = array();
echo "<script>window.location.href='Contact_Us.php#myForm'</script>";
} else {
unset($_POST);
}
There are no error messages.
The page appears to refresh and the code to unset the POST variables fails.
If you really want to do things that way simply drop out of PHP instead of trying to echo things.
if (isset($_POST['name'])) {
$_POST = array();
?>
<script>window.location.href='Contact_Us.php#myForm'</script>
<?php
} else {
unset($_POST);
}

How to restrict $_SESSION[] using Javascript?

I wanna get just $_SESSION["yetki"] value when I call users function actually I am getting value but always getting "manager" value even if user equal student .
<script>
function users(tik) {
var user = tik.id;
if(user === "student")
{
<?php $_SESSION["yetki"]="student"; echo $_SESSION["yetki"]; ?>
}
else ()
{
<?php $_SESSION["yetki"]="manager"; echo $_SESSION["yetki"]; ?>
}
}
</script>
What you are doing is completly wrong, you are mixing both client side and server side code, javascript is client side code and php is server side language. In your if else condition you need to send request to server to set that session variable. For sending request to server you can use ajax.
Actually, you got all your fundamental understanding of Php and JavaScript wrong. By the time that this script is already running in the client's web browser, the Php scripts would have been processed/executed already and echoed into the document body.
Here's how it works. When you ask for a Php "page", the server would execute every Php script in that page and generate a response. That response would be the one that your web browser would execute.
for example, if you do this:
<script>
if (<?Php echo "true"; ?>) { alert ( 'The server said true' ); }
else { alert ( 'The server didn't say anything' ); }
</script>
The one you'll see in your web browser is:
<script>
if (true) { alert ( 'The server said true' ); }
else { alert ( 'The server didn't say anything' ); }
</script>
What Php does is to create dynamic contents for the webpage and send it back to the client. The client's web browser would then execute the result of that generated content. The Php codes would all be executed as soon as you requested for the web page - the process all happens in the server. JavaScript, on the other hand, would execute AFTER the client receives the web page.
In fact, "echo" is a pretty descriptive term of what Php does. When you type a web address in your browser's address bar and press enter, you are sending a request to the server. Once it "hits" the server, it will "echo" a response in the form of HTML. That HTML would then be read by your web browser and that would include everything from Javascript to CSS. And yes, you can even echo a whole mix of HTML elements and Javascript content. You can even echo the whole document body.
for example:
<?Php
echo
<<<YOURCONTENT
<HTML>
<HEAD></HEAD>
<BODY>You're gonna love my body.</BODY>
</HTML>
YOURCONTENT;
?>
WHAT YOU SHOULD DO FIRST is to validate what the contents of $_SESSION["yetki"] would be.
<?Php
if(your conditions here)
$_SESSION["yetki"]="student";
else
$_SESSION["yetki"]="manager";
?>
<script>
function users(tik) {
var user = tik.id;
if(user === "student")
{
alert('<?php echo $_SESSION["yetki"]; ?>');
}
else
{ // I DON'T KNOW WHAT YOU'RE TRYING HERE, BUT LET'S DO AN ALERT.
alert('<?php echo $_SESSION["yetki"]; ?>');
}
}
</script>
possible conditions for Php if statement:
$_POST['yourFormInputName'] == 'yourRogueValue'
or
$_GET['yourURLVariableName'] == 'yourRogueValue'
or
$_SESSION['perhapsAnotherStoredSession'] == 'yourRogueValue'
you can do with something like this.. but don't know is this a good answer
<script>
function users(tik) {
var user = tik.id;
if(user === "student")
{
var aa = "<?php $_SESSION["yetki"]="student"; echo $_SESSION["yetki"]; ?>"
}
else
{
var aa = "<?php $_SESSION["yetki"]="manager"; echo $_SESSION["yetki"]; ?>"
}
alert(aa);
}
</script>

Creating a javascript alert with php that has a php variable inside?

I'm making a form that is supposed to create a javascript alert when some fields aren't filled out or filled out properly. I want to be able to take the error messages I've put in a php variable and display them in the javascript alert window.
The following code does not work:
function died($error) {
echo '<script type="text/javascript"> alert('.$error.')</script>';
die();
}
How can I add the string contained in $error between the two "script" strings so it will output properly as a javascript alert?
Thank you!
You only forgot quotations that are required for the JavaScript alert.
If you passed 'hello' to the function, your current code would create alert as:
alert(hello)
instead of doing:
alert("hello")
Therefore, change your line to the following (two double quotes are added before and after concatenating $error):
echo '<script type="text/javascript">alert("'.$error.'");</script>';
and you can use your function:
died('error on whatever');
Display variable php in alert javascript
<?php
function died($error) { ?>
<script>alert("<?php echo $error; ?>")</script>
<?php die();
} ?>
You can use function follow this:
function died($error) {
echo '<script> alert("'.$error.'")</script>';
die();
}
<?php
echo "<script type='text/javascript'>alert('{$_SESSION["success"]}');</script>";
unset($_SESSION["success"]);
?>
Use this code it would work correctly

PHP function return value to JavaScript

I need to send result from my PHP file to the JavaScript function/file.
I found some of answers like: var x='<?php echo $pathinfo; ?>';
or this:
myHtmlFile.html:
<script type="text/javascript" src="jquery-1.8.1.js"></script>
<script type="text/javascript" src="newEmptyPHP.php"></script>
<script language="javascript">
function test()
{
alert(result);
}
</script>
newEmptyPHP.php:
<?php
$res="it is result";
echo "var result = ".json_encode($res).";";
?>
My question is whether there is way return value from php function and not from php file.
something like this:
<?php
function phpFunction(){
$res="it is result";
return $res;
}
?>
I need simple PHP/JavaScript code without something complex.
I want keep many function in one php file and not many php files.
<?php
function phpFunction(){
$res="it is result";
return $res;
}
?>
<script>
var result = "<?php echo phpFunction() ?>";
</script>
The above method will work. However, if you want more PHP/JS combined scripts, learn AJAX.
The best way to get your data to JavaScript from PHP is to use AJAX using jQuery you have declared.
You can use $.get()
You can call you php script which contains the function with parameters in you url request.
And when a specific parameter is specified in the url, then you can call you fonction and echo whatever you want to the javascript.
Have a good day!
You can open as many php tags as you wish inside your one php document. You can then either make this php document separate from your main document (however this would require making the main document in php and using a "php include" or "php require") or you can simply just open and close php tags as necessary. You do not even have to close the line at the end of the php, for example.
<?php if (a==a) { ?>
<div>
<script>
<?php echo 'do something here'; ?>
</script>
</div>
<?php } ?>
Using the above example can provide some unique results. Just remember that anything you do with php you can just echo out the result and slot it into the middle of your javascript.

Pass php variable via js/jquery redirect url function

In my php i'd like to redirect via javascript/jquery a url with a php variable via js function.
My js function
function Redirect(url){
document.location.href=url;
}
In my php page i try in this way but I fear there is a problem with the syntax in the $url.
if ($opz = 1){
$url = "index.php?opz=OK#PG2&id=" . $_GET['id'];
echo "<script>";
echo "$(function(){ Redirect($url); });";
echo "</script>";
}
If I try to redirect in this way everything works perfectly (no Redirect function).
echo "<script>
document.location.href='index.php?opz=OK#PG2&id=$_GET[id]'
</script>";
Can anyone suggest me what is the correct syntax to pass my php variable via the js Redirect function? Thanks.
Just change echo "$(function(){ Redirect($url); });"; to
echo "$(function(){ Redirect('$url'); });";
Notice the quotes. the url is to be passed to the Redirect function as a string. So enclose it in single quotes. like Redirect('$url');
your problem is simple:
echo "$(function(){ Redirect($url); });";
should be replaced with
echo "$(function(){ Redirect('$url'); });";
Why you are trying to redirect your webpage using javascript.
You can do it with PHP also. Use PHP header() function to redirect your page.
if ($opz = 1){
$url = "index.php?opz=OK#PG2&id=" . $_GET['id'];
header("Location:".$url);
}
Assuming the Javascript code being generated is OK try window.location
try like below
if ($opz = 1){
$param = 'opz='.urlencode("OK#PG2").'&id='.$_GET['id'];
$url = "index.php?".$param;
echo "<script>";
echo "$(function(){ Redirect($url); });";
echo "</script>";
}
and pick up opz using urldecode();
The problem is caused by the fact that your generated HTML looks like this:
Redirect(index.php?opz=.....);
As you can see, you're missing quotes.
To put a variable from PHP into JavaScript, I always use json_encode. This ensures that, no matter what I pass it, JavaScript will see the same thing. It takes care of quoting, escaping, even iterating over arrays and objects.

Categories