echo javascript from php not working? - php

So, in an html page I'm trying to have a php segment echo some javascript code, as seen here:
<?php
echo "This was legitimately hit";
if(!empty($_POST['name']))
{
echo '<script type="text/javascript">alert("We got the name");</script>';
}
else
{
echo '<script type="text/javascript">alert("We DID NOT get the name");</script>';
}
?>
and from what I've read online, this seems to be a legitimate way of doing things, but the page seems to be reading the first part up until the first closing chevron (seen just below here) as a comment.
<?php
echo "This was legitimately hit";
if(!empty($_POST['name']))
{
echo '<script type="text/javascript">
Then it reads the else and next echo as plain text, and puts it on the webpage. the next javascript code block then gets read as a regular javascript code block, so the page does a pop-up saying it did not get the name. The closing bracket and closing chevron then just get output as more text.
So in the end the page just ends up having
alert("We got the name")'; } else { echo ''; } ?>
printed on it as plain text, and has a pop-up that says we received no name.
What is going wrong here?

Sounds like the file isn't being processed as PHP. Does the file name end in .php? Are you sure PHP is installed and hooked up correctly to the web server?
edit: To handle the Facebook requests in the same page:
<?php
if (isset($_POST['facebook_request_field'])) {
// handle the Facebook request, output any necessary response
// then exit
exit;
}
?>
<!-- display the web page normally here -->
So for your test page:
<?php
if (isset($_POST['name'])) {
echo '<script type="text/javascript">alert("got a name!");</script>';
exit;
}
?>
<script type="text/javascript">alert("No name.");</script>
(That's actually identical in function to what you already have, so maybe I'm misunderstanding the purpose.)

Between We got the signed request and We got the name, I think you haven't given us the actual code that's causing the error. Double check that, and make sure you don't have any stray single quotes before your alert call.

There are missing ; after the alert. Have you tried correcting this first?

Related

Loading PHP function using jQuery onclick

I am trying to hide our mailing address on our website, until someone cliks a button to "load" the address. I am doing it like follows:
Homepage.php:
<button onclick="test()"> Click </button>
<div> </div>
<script>
function test(){
$.ajax({url:"address.php", success:function(result){
$("div").text(result);}
})
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
Address.php:
<?php
function php_func(){
echo '<span><?php echo $address; ?></span>';
}
php_func();
?>
This works in echoing the text onto homepage.php, but it's not loading the PHP function. Just showing the function as text as seen here:
I tried $("div").write(result);} and it won't even load.
$address is already defined elsewhere. Any tips?
You're trying to write code which outputs code which outputs the address. Why? You're already in the context of outputting something from the PHP code:
echo "something...";
If what you want to output is the value of $address then just output that:
echo "<span>$address</span>";
I suspect the reason you did it that way is because you're expecting the currently loaded page to parse and execute that PHP code. This is a fundamental misunderstanding of how these technologies work. The PHP code for that page executed once, on the server, and delivered the resulting HTML/CSS/JavaScript to the client.
The AJAX operation is making a new, separate request to another PHP resource which will execute on the server and output back to the client. In this case it's just outputting a string value, which the client-side JavaScript code will then write to an element on the page:
$("div").text(result);
(This is a good opportunity for you to use your browser's debugging tools and observe the AJAX request/result in the network tab, to see what's actually being sent/received. At no point should actual PHP code be visible to the browser. All of that is executed on the server.)
The reason this is important is because, if this is the case, then you are likely misunderstanding where $address is defined. If it's defined in the PHP script which rendered the page you're looking at, that doesn't mean it's defined in address.php. If the code you're showing us for address.php is the entirety of that page then $address is not defined.
So you'll need to define $address on that page.
After having said all of that... You might find it much easier not to involve AJAX for this at all in the first place. Just output the address to the page but style the <span> to not be visible. Then when the user clicks the button, make it visible. No need for the complexity of an entirely new HTTP request:
$('button').click(function () {
$('span').show();
});
span {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>Click</button>
<span>this is the address</span>
You don't use <?php echo inside strings; that's only used when you're in a section of the script that's outputting literal text, not executing PHP code.
If you're in PHP code doing echo, you use variable substitution or concatenation.
<?php
function php_func(){
echo "<span>$address</span>";
}
php_func();
?>
You'll need additional code to set the $address variable; I assume you just left that out for simplification in the question.
<?php
function php_func(){
echo '<span>' . $address .'</span>';
}
php_func();
?>
this should work, u can't use 'echo' and inside echo open 'php' tag to use again.... more another 'echo'

How to combine this PHP code with HTML and Javascript?

for example, this is my PHP code:
<?php
if($country_code == 'US')
{
header('Location: http://www.test.com');
}
else
{
header('Location: http://www.test.com/');
}
?>
I'm trying to use a Javascript code for tracking, it has to be above the </body> tag.
I have tried different ways of combining the PHP code with HTML, I have tried placing the HTML separately below the PHP also, one example:
<html>
<head></head>
<body>
<?php
?>
<script></script>
</body>
</html>
The furthest I got was, it tracked the click but it didn't redirect giving me this error:
`Warning: Cannot modify header information - headers already sent by`
Will appreciate any suggestions and help, thank you!
Put the php redirect code at the begining of your document before anything is outputted. Check for spaces after the ?> tag and before the <?php tag because these will be printed out and the response header will be sent therefor you will not be able to modify the header to redirect.
You have to try something like the following to track:
<?php
if($country_code == 'US')
{
header('Location: http://www.test.com/?us=yes');
}
else
{
header('Location: http://www.test.com/?us=no');
}
?>
And then in your index page check for the value of the us parameter. Also you should Notice that there is no any output should be printed before the header function to void the warning :
Warning: Cannot modify header information - headers already sent by
The trouble is that PHP run before JavaScript. So you need to geet the PHP variable inside a JavaScript.
<?php
// your normal code here, like connection to DB
?>
<script>var test = <?php> echo $thatVariable; <?> </script>
You may not send an output to the client before a header() tag of php.
So you can generate a redirect page which gets the country information via js and send it to the php (using e.g form submit). after that you can redirect to the accoording page via php header()
<?php
if($country_code === 'US'){
echo "<script> window.location.href='http://www.test.com1'</script>";
}
else{
echo "<script> window.location.href='http://www.test.com2/'</script>";
}
?>

Issues with calling a JavaScript function from PHP

I have created a form to upload a a newsletter into the database. I'm using the iFrame method to post the date without the page refresh and I'm displaying a nice jQuery dialog for the loading.
I am now having issues with closing that dialog when the upload is complete. All the tutorials I have read online say that I must just echo out the code like this:
<?php
echo "<script type='text/javascript>uploadComplete();</script>";
?>
Now the JavaScript does run when I do something stupid to test like just echo out an alert, but when I try and call any function or just go straight to the jQuery to close the dialog it just says that the function is not defined. I can post my code if it is necessary, but it's pretty standard and I didn't think I would need to in this kind of example.
Any help would be appreciated! Thanks in advance.
you forgot ' in the end of 'text/javascript'
echo "<script type='text/javascript'>uploadComplete();</script>";
NB : the type attribute is entirely unnecessary if the script is JavaScript
using just php
echo '<script type="text/javascript">'
, 'jsfunction();'
, '</script>';
escaping from php mode to direct output mode
<?php
// some php stuff
?>
<script type="text/javascript">
jsFunction();
</script>
I eventually solved this by using the following code:
<?php
echo "<script type='text/javascript>top.uploadComplete();</script>";
?>
The "top" keyword just solved all of my problems. I hope this helps whoever has the same issue I had!

popup window not work in php echo

it can appear a simple question but i have searched untill writing here but no answer. i have a php code and i what to start a pop up window after echo :
echo "<A HREF='map2.php' onClick='return popup(this,'notes')'>WHATEVER</A>";
in the head section i have :
<SCRIPT TYPE="text/javascript">
<!--
function popup(mylink, windowname)
{
if (! window.focus)return true;
var href;
if (typeof(mylink) == 'string')
href=mylink;
else
href=mylink.href;
window.open(href, windowname, 'width=400,height=235,scrollbars=yes');
return false;
}
at the end is the ending script tag but i dont succide in adding it.
anyway.the pop up doesn work. the link opens in the same page.
i also tried :
About
and it doesnt work. it opens in the same page. The funny thing is that all these 2 solutions worked in html page, but when used between php , after "echo" , it doesnt work anymore.
In the first line you posted (the php echo), it seems to me you have a problem with ' in side '
Try the following:
echo "WHATEVER";
The issue here your quoting.
When outputting HTML I recommend using single quotes with echo as it allows you to use the proper double quotes for the HTML tags.
echo 'Whatever';
The problem with your original code was that you had quotes within quotes that were breaking the syntax. Read the link I posted to see how to handle quotes properly with PHP.

redirect without page reload

I want to redirect error message to index page so i wrote the following code:
$message="Bad answer, go back to page!";
header("location:index.php?message=".$message);
this code in process page, and i'm fetching data in index.php page like:
<?php
if(isset($_GET['message'])) {
$message=$_GET['message'];?>
<?php echo $message; ?></iframe>
}
else { echo ""; }
?>
i tried to display message in iframe....but i couldn't succeed.
Your echoing the iFrame tags incompletely/incorrectly. Try this
<?php
if(isset($_GET['message'])) {
$message=$_GET['message'];
echo '<iframe>'.$message.'</iframe>';
}
else { echo ""; }
?>
When you are talking about DOM manipulation (without needing to refresh the page), you should know the best, most elegant way is to do that with Jquery / Ajax / PHP.
Use $.get or $.post to send data to PHP and get the returned data (this case : Bad answer, go back to page!)
Get your <div> or <iframe> element and load the returned data inside of your selected element with Jquery.
I don't know if you are willing to do some changes. If you are willing to do more changes, please drop a comment so I will give you a code example about it.
Some Information you must know;
$.get and / or $.post.
.load() to load returned data.
I hope this helps.

Categories