I am trying to start a javscript annimation and then submit a form. I have this but it's not working... I understand php is server side and javascript is client side; however, this works with alerts as long as I get rid of the header so I am confused why it wont work with my annimation.
if (isset($_POST['play'])) {
if ($mSecs >= .1) {
echo "<script>
spinWheel_1.startAnimation();
</script>";
}
sleep(5);
header("Location: winwheel.php");
}
You instruct the browser to immediately navigate away by sending the header. This is the reason why you see your animation without the header in the script.
Also, note that you cannot send the header after sending any output as a response.
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
Related
I am using below code for redirect users.
<?php
$redirect_to = "https://google.com";
$redirect = "https://yahoo.com";
echo "<script>location.href = '".$redirect_to."';</script>";
header("Location: $redirect");
exit();
?>
I prefer to use javascript redirect, but in somecase when user have not javascript enabled in his browser, I am using PHP redirect as backup redirect but sometime I am getting header already sent error on php redirect code and sometime I am not getting that error.
if I use exit() after redirect by javascript, I will not able to
redirect user if he have javascript disabled in his browser.
my question is there any way to stop php code if javascript redirect was success? I am not getting idea what I have to do for handle my situation.
Let me know if any expert can help me to solve puzzle.
Thanks!
Well, you are a web developer using PHP and Javascript.
One thing to remember, PHP code always runs first on the server. It's a server-side language, so no matter how you arrange your lines of code, your php code will finish running. Then, the client source code (HTML, CSS, JavaScript) is sent to the browser and executed on it (Client-side).
And next, the job of redirecting is always on the client side, the server doesn't actually redirect people to another site. What actually happens is that your php source code generates a redirect command that sends the browser for a redirect.
Another thing, in php, any work related to the header() function needs to be executed before any content is generated. That is, it must run at the top, before any method echo, exit, print,... or content block.
When deploying a php application, if you already use header("Location: ....") then it makes no sense to use javascript directives, as the browser will prioritize handling the redirect in the header first! !
The source code should really be:
<?php
$redirect = "https://yahoo.com";
header("Location: $redirect");
?>
Another way if you still prefer using javascript redirects and are compatible with javascript disabled, that is to use the tag meta[http-equiv="refresh"]. Refer to the following example:
<?php
$redirect_to = "https://google.com";
?>
<meta http-equiv="refresh" content="5;URL='<?php echo $redirect_to; ?>'" />
<script>location.href = "<?php echo $redirect_to; ?>";</script>
The number 5 appears in the content of the meta specifying the countdown (seconds) the browser will redirect when the page has finished loading. When the page cannot execute javascript, after 5 seconds the page will redirect.
When I call a PHP function from a javascript function (located in an .js external file), the webpage refreshes and appears to stop loading at the PHP function.
function completePurchase(){
//check if perosn signed in
if (signedIn){
alert("Purchase Complete! Total : " + total);
//Upadte database - call PHP function in MainPage2
document.write('<?php echo upadtePurchaseToDB();?>');
}
}
The PHP function resides in the PHP page enclosed within PHP tags:
//PHP to handle data when purchase button is pressed
function upadtePurchaseToDB(){
echo "PHP CALLAED AS PURCHASE BUTTON PRESSED";
};
The idea is to update a database when the PHP function is called.
However when called the page refreshes and remains blank.
In the console if i navigate to the 'Element' tab I can see the PHP call:
Not sure what the underlying issue is wether its how I have called the PHP function using JS or where the PHP function is placed.
One problem is that you're trying to make JS genarate PHP code, and then expecting that to work: it can't. PHP runs on the server, and only "does things" when asked for a page by the browser: PHP generates source code for the browser to deal with. That's all it does.
When the browser has the page, JS kicks in, and PHP is no longer anywhere to be found: see Difference between Javascript and PHP for more information on this, and I can strongly recommend reading up on that.
However, the real problem that you're describing (your page seemingly reloading but dying on the PHP code) is one caused by your use of document.write(), which absolute doesn't do what you think it does, and you should not be using it in modern code.
document.write is one of the earliest functions in JS and is super low level: it does not write text into a webpage, it writes bytes into the document bytestream so that the document parser can pick up data from the bytestream at the same time and parse it into a page tree.
While the page is still being processed, that seems safe: document.write will simply inject bytes into the open bytestream, and the parser will parse that, and all will seem well. However, once the page tree is done and the document bytestream gets closed, things start to go very, very wrong:
Any call to document.write will try to write into the open bytestream, and if it's closed, document.write will simply open a bytestream: now you have an empty document bytestream. And because the document parser sees an open bytestream, it start building a page tree based on what's in it, and now your page is gone because that's what you told the browser to do.
It's also not the case that it "appears to stop loading at the PHP function", what actually happens is that you've told the page parser that the new page code to form a page tree off of is the byte sequence <?php echo upadtePurchaseToDB();?>. So the parser looks at that, sees <, and so knows that what comes after that will be a tag, because that's how HTML works. It then sees ? and goes "Error: this HTML is invalid HTML" and stops.
So the bottom line here is to read up on where and when PHP runs, vs where and when JS runs, but arguably even more importantly: never use document.write because it doesn't do what you think, at all.
I have recently moved from localhost to my live website. I have a simple PHP login page. After the users details are checked with my mysql table and if the username exist and they provide a valid password for that username they are redirected to the home page. I was using the header function built in to PHP but this seems to be no longer working now that I am on my live website.
After further research it seems that I cannot use header tags after the page loads. So I am not echo'ing out script tags to window.location redirect to my homepage. The problem with this is that when the new location is being redirected to it appears to look like an additional web pages is loading in before my actual webpage that I'm wanting to go to loads in (This is probably due to the fact that I have extra error handling code that is running after the fact). Does anyone else experience this when using this method? Is there a better way to handle this?
This is what I'm using currently just in case there is any confusion
echo '<script>window.location.href = "home.php";</script>';
I was using the header function built in to PHP but this seems to be
no longer working now that I am on my live website.
Headers must be the very first thing that your script outputs or they won't work. PHP has a convenience feature called output buffering which temporarily holds back the output until the script is done. This allows you to put calls to header() anywhere in your code, and then PHP will automatically take care of moving headers to the front of the output for you. Thus, if you have output buffering enabled, you can put headers anywhere and it will still work. If you do not have output buffering enabled, you must put headers at the very start.
I will wager that you are generating output before the headers, and your local PHP install has output buffering enabled, while your remote host does not. You can fix this in one of two ways:
Update your code to ensure that nothing is output before calls to header().
Enable output buffering on your host by setting output_buffering = 1 in your php.ini.
I recently learnt you can do this with a meta tag:
<meta http-equiv="refresh" content="2;url=http://example.com/" />
I have a js script that uses ajax to post data to a php script. The php script will open a text file and write the data that's passed from the js script. The same script works on chrome on a different machine but after I migrate it to the server where only IE is available, it does not work.
After executing the POST script in js, my browser shows the success message but the data in the text file is not changed. One problem I can think of is the directory I put in my php script is not correct. So I added these lines from w3schools to see if the file is actually found, but nothing peculiar happened:
if(!file_exists("welcome.txt")) {
die("File not found");
} else {
$file=fopen("welcome.txt","r");
}
What are some other ways I can do for debugging in this case?
UPDATE
I think my php in general is not working for some reasons. I have replaced everything in my php file with
echo '<script type="text/javascript">alert("hello"); </script>';
I am assuming when I click the button on my webpage, the js will do a $ajax post and the php script will be executed showing the alert message. However nothing yet shows up
In a PHP script you can turn error reporting on with:
error_reporting(E_ALL);
ini_set('display_errors', 1);
Error and warnings will show up that will give you possibly a hint where your script is failing.
I'm busy doing server side and client side validation for magento. this validation works fine on server side (php)
on the client side i am using javasrcript.
When i started on this. i had my javascript embedded on a phtml file and everything was working as expected.
because i am using magento so I decided to inject the javascript file via page.xml
When I added the javascript code instead of getting the message pulled I get the php as is.
Here is my javascript:
function DefaultAddressErrorChangeNotAllowedMessage() {
alert("<?php echo Mage::helper('invent_general')->getDefaultAddressErrorChangeNotAllowedMessage();?>");
return;
}
I run this when a user hit the onclick it will point to this function DefaultAddressErrorChangeNotAllowedMessage()
and the
<?php echo Mage::helper('invent_general')->getDefaultAddressErrorChangeNotAllowedMessage();?>
will be populated as is.
but when I embed this directly to a phtml file it pull the correct message.
I there a way for javasrcipt that I can use to escape the php and get the correct message which is pulled from config.xml
PHP is rendered server side only. If you need to "inject" PHP specific values to your javascript, then you either need to render the actual value as part of the output of the php script, or you need to take a new roundtrip to the server, using Ajax.
Javascript is clientside, PHP is server side, so all php has been evaluated when javascript is loaded. This means, you can alert php echos, but you can't run PHP operations or any PHP logic in Javascript. You need ajax for this.
sorry for my clumsy answer, but maybe you lost the simple things.
I see that your javascript contains php tag, so i think you should insert your javascript code into .php extension because .js extension can't recognise the php tag.