Reputation: 19366
I'd like to send headers with PHP, inside of a javascript condition. Is that possible?
if ($('body').hasClass('browserChrome')) {
<?php
header("Content-Type: application/x-chrome-extension");
header('Content-Disposition: attachment; filename="http://example.com/file.crx"');
header("Pragma: no-cache");
header("Expires: 0");
?>
}
Upvotes: 1
Views: 332
Reputation: 985
It seems as if you are trying to download a file through javascript, more like, push the file to the client browser. However, as it has been answered, its not possible for the code to work, as it happens on the server, and js runs on the client.
To achieve that, you would need to use javascript itself, ajax in this case, to download the relevant content.
You may find how to download file from javascript here : http://www.codeproject.com/KB/scripting/FileDownloadUsingJScript.aspx
Upvotes: 1
Reputation: 800
if you need send some headers from JS(only), you can use method setRequestHeader of object XMLHttpRequest
new XMLHttpRequest();
//or
new ActiveXObject(...) for IE
...
xmlHttp.open(...
xmlHttp.setRequestHeader("Cache-Control", "no-cache, must-revalidate");
xmlHttp.setRequestHeader("Pragma", "no-cache");
or can use some method JS frameworks (jQuery, Prototype, etc,)
But as has already been answered, is not correct write php code in js
Upvotes: 2
Reputation: 77732
That won't work. First, your web server will execute the PHP script, resulting in an HTML page with JavaScript. That is then sent to the user's web client, which will display the HTML and execute the JavaScript. There is no trace of the PHP code by the time the JavaScript interpreter gets to it.
Upvotes: 3
Reputation: 413720
No, it is not possible. (Well, more like, it's not meaningful or useful, and will likely cause page errors.)
The php code runs on your server before the page is sent out, like a baby in a stork bill, on its way to the client browser. The stork flies for a long time, through good weather and bad, storms, ice, snow, hunting parties, and pollution. At long last, the stork reaches your customer as they wait patiently for their new baby web page to appear.
Then, suddenly, -~ p00f ~- and the page arrives. At this point, the JavaScript in the page runs.
Upvotes: 2