How to combine this PHP code with HTML and Javascript? - php

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>";
}
?>

Related

How can I put an Html <form> tag inside a PHP function, which would redirect me to another .php file?

I have been searching for hours on the web and I just can't seem to find an answer.
What I want to do is put a <form> tag inside a php function which would redirect me to another x.php file if a certain criteria is met.
Sounds simple enough:
function myFunction() {
if ( Some Condition Here ) {
?>
<form action="x.php">
<button>submit</button>
</form>
<?php
}
}
Obviously the "redirect" won't happen until the form is submitted. Redirecting is done in response to an HTTP request not to "having a form".
You don't use form to redirect , you use a header
function redirect(url){
header("Location: ".url);
die();
}
so now
if(some_condition){
redirect("anotherFile.php");
}
For redirect use following code:
header('Location: page.php');
exit;

Do not want Html after php is executed

I have the following code:
<?php
...
?>
<script>
....
</script>
<html>
...
</html>
After displaying HTML form, JavaScript should validate and then PHP should save in database and give a confirmation message.. but what happens is, after PHP is executed and success message is echoed, the HTML form also displays as it is below message..
What can I do to avoid this?
I prefer to set a variable if a form submission was successful. Something like the following:
<?php
$success = false;
if (isset($_POST['submit'])) {
// process form submission
// if submission validates; set $success to true
}
?>
<!DOCTYPE html>
<html>
<head>
…
</head>
<body>
<?php if ($success): ?>
<p>Thank you for your submission!</p>
<?php else: ?>
<form action="" method="post">
…
</form>
<?php endif; ?>
</body>
</html>
if(isset($_POST['name'])){
//your insert query
//your thanks message
}
else{
// Your html form
}
Simply use a flag variable :-
if(isset($some_var))
{
// do something
}
else{
// show html form
}
You could end the script after progressing the data with exit(); (See docs)
Like #Shomz said, you could wrap your HTML output in a if-statement to prevent it from being printed after processing your form data.
You can use the 'action' of your form to send the post to another file where there is the confirmation message.
Or you cant put a condition if(!$_POST) before your html
put PHP in a different file (you can include HTML files)
return;
die();
exit();
Use ob_start() and functions alike to buffer HTML and _clean to flush it to nirvana when you don't need it.
Submit to a different file (nearly the same as first point).
Use prepend in php.ini to start ob before script, and append in php.ini to kill output under certain circumstances (maybe using isset() on a variable to check if there has been a submit or just $_POST / $_GET ).
You might also want to look at PRG pattern which someone else has already asked about for php here: Simple Post-Redirect-Get code example

echo javascript from php not working?

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?

PHP refresh window? equivalent to F5 page reload?

Is there anything in PHP that is the equivalent of manually pressing the F5 page reload button? My php script is in a frame and isn't the parent script but it needs to refresh the entire page and not just it's frame.
Actually it is possible:
Header('Location: '.$_SERVER['PHP_SELF']);
Exit(); //optional
And it will reload the same page.
With PHP you just can handle server-side stuff. What you can do is print this in your iframe:
parent.window.location.reload();
If you have any text before a
header('Location: http://www.example.com/youformhere.php');
you'll have issues, because that must be sent before any other text is sent to the page.
Try using this code instead
<?php
$page = $_SERVER['PHP_SELF'];
echo '<meta http-equiv="Refresh" content="0;' . $page . '">';
?>
Just remember, this code will create and infinite loop, so you'll probably need to make some conditional changes to it.
PHP cannot force the client to do anything. It cannot refresh the page, let alone refresh the parent of a frame.
EDIT: You can of course, make PHP write JavaScript, but this is not PHP doing, it's actually JavaScript, and it will fail if JavaScript is disabled.
<?php
echo '<script>parent.window.location.reload(true);</script>';
?>
<?php
echo "<script>window.opener.location.reload();</script>";
echo "<script>window.close();</script>";
?>
with php you can use two redirections.
It works same as refresh in some issues.
you can use a page redirect.php and post your last url to it by GET method (for example).
then in redirect.php you can change header to location you`ve sent to it by GET method.
like this:
your page:
<?php
header("location:redirec.php?ref=".$your_url);
?>
redirect.php:
<?php
$ref_url=$_GET["ref"];
header("location:redirec.php?ref=".$ref_url);
?>
that worked for me good.
Use JavaScript for this. You can do:
echo '
<script type="text/javascript">
parent.window.location.reload(true);
</script>
';
In PHP and it will refresh the parent's frame page.
guess you could echo the meta tag to do the refresh in regular intervals ... like
<meta http-equiv="refresh" content="600" url="your-url-here">
All you need to do to manually refresh a page is to provide a link pointing to the same page
Like this:
Refresh the selection
Adding following in the page header works for me:
<?php
if($i_wanna_reload_the_full_page_on_top == "yes")
{
$reloadneeded = "1";
}
else
{
$reloadneeded = "0";
}
if($reloadneeded > 0)
{
?>
<script type="text/javascript">
top.window.location='indexframes.php';
</script>
<?php
}else{}
?>

Javascript alert instead of redirect in PHP mail script

Thanks to Col. Shrapnel I am using a VERY basic PHP script to send emails. The form is located here.
This is the script:
<?php
mail('JBIRD1111#gmail.com','Live Date Submission',implode("\n\n",$_POST));
header("Location: thankyou.html");
?>
When a user submits the form, they are redirected to a thankyou.html page. I want to edit the code to display a javascript alert, instead of a redirect. I don't have much PHP knowledge, so how would I edit this code to return a alert instead of a redirect?
Actually, if you want to send a Javascript alert instead I would recommend using some basic jQuery work. I would also take a look at the AJAX section of the documentation.
Otherwise you can inset some javascript in the original form page.
session_start();
$_SESSION['message'] = "<script>alert('Thank you so very much! You rock!');</script>";
header("Location: originalformpage.html");
and on the original form page
session_start();
if(isset($_SESSION['message']))
{
echo($_SESSION['message']);
unset($_SESSION['message']);
}
Replace the header line with:
print("<script>alert('Thank you so very much! You rock!');</script>");
Not tested but should work.

Categories