I want to call a PHP file but want to pass an argument to the PHP file. Not getting the correct approach, I am attempting to write a cookie and read that cookie when the PHP file loads. But this is also not working. I am using following code to write and read cookie. I just want to test the read cookie function of JavaScript here. I know how to read the cookie value in PHP.
<script>
function SetRowInCookie(NewCookieValue)
{
try
{
alert(NewCookieValue);
document.cookie = 'row_id=' + NewCookieValue;
loadCookies();
}
catch(err)
{
alert(err.description);
}
}
function loadCookies() {
var cr = []; if (document.cookie != '') {
var ck = document.cookie.split('; ');
for (var i=ck.length - 1; i>= 0; i--) {
var cv = ck.split('=');
cr[ck[0]]=ck[1];
}
}
alert(cr['row_id']);
}
</script>
I'm not sure what in your code (running on the client's PC) you expect to cause the php script (running on the server) to run. You'll need to invoke the php by making some kind of http request (like get http://yoururl/recheckcookie.php). With at HTTP request, the javascript code on the client to queries the webserver for the output of your recheckcookie.php script. This script can then recheck the cookie, and return some/no output.
Look up XMLHttpRequest or preferably the corresponding JQuery to see how to perform the HTTP request.
Cookies are not the way to transfer variables between client and server. you should append key/variables pairs to your request URL using either a get (querystring) or post method.
jQuery ajax example;
$.get('http://www.myphpserver.com/script.php?row_id=' + NewCookieValue);
I think, you dont need cookies. try it with $.post, where you can define which url will be called, something like:
$.post(url, params, callback_function);
Well I'm not sure what it is you are ultimately trying to achieve but it sounds like using AJAX could be your solution. There is a good tutorial here.
AJAX will basically allow you to call a php script, pass it variables and then use it's output on your webpage.
Related
Is there a way to pass javascript value to php?
if(echo '<script>window.location.href="/mysite"</script>' === "/mysite"){
$myVal = 1;
}else{
$myVal = 2;
}
This way seems doesn't work
Nope you can't do it. If you want something like that best and easiest way is using JQuery ajax function http://api.jquery.com/jQuery.ajax/ which will send request to server with data you want to given script (easiest way - make other .php file?) and if you want something returned, it will be in ajax returned data. Read provided link and you should be good to go.
If you want to know on which site you are currently (as in example) you can use $_SERVER array and get variable which you want from it. List is here: http://php.net/manual/en/reserved.variables.server.php
PHP code executes server-side. JavaScript executes client-side. There's no way for the two to communicate unless you create a web service in PHP that is called from the JavaScript. Unfortunately that won't solve your problem.
If you're trying to set values based on the requested url, you could try:
if($_SERVER['REQUEST_URL'] === "/mysite"){
$myVal = 1;
} else {
$myVal = 2;
}
The code I see in your post shows that you completely misunderstand PHP and Javascript nature.
Send JS var through AJAX request and then work with it in some server-side script.
php is executed on the server side first.
then javascript is executed on the client side. So it's after the php has been rendered.
The only way to send javascript values to php, is using ajax to send an asynchronous call.
I want to transfer the varible "content" to php and then a mysql database, but everything I have tryied fails. The data is comming from a iframe and the code looks like this
function getContentFromIframe(Textfield)
{
var myIFrame = document.getElementById("Textfield");
var content = myIFrame.contentWindow.document.body.innerHTML;
if (content != "")
{
alert('bla, bla, bla ' + content);
content = 'The inside of my frame has now been saved';
myIFrame.contentWindow.document.body.innerHTML = content;
}
else{
alert('bla bla bla ');
}
}
Sending data from the browser to the web server is not such a simple task. I would suggest you read up on AJAX. Basically AJAX will allow you to send asynchronous request to the server from you JS code. The data you want sent is added as POST body or as query parameters in the URL you request, depending on the size of the data.
Also using AJAX without some extra library (Prototype/JQuery/etc) is not very easy, due to cross-browser issues. Check those out too.
Save javascript data in hidden field and get hidden field in php code
You will need to perform a request that interfaces with your server in some way. You can use a form submission, or put the variable in the query string of a URL and navigate to it (using window.location). Or an AJAX request.
I needed recently to set some $_SESSION vars from onSelect on a select menu. So basically, transferring Javascript value to PHP.
It's totally doable through AJAX, and I use the simple object inited in Javascript (no JQuery or other new fancy tools for cool programmers :))
You can actually do an AJAX request, via POST or GET (read docs on AJAX), and then in the .php file on which you do the request, init a $_SESSION var (with start_session() on) which you can then access in your PHP current page.
Basically, to shed some more light, when you trigger a Javascript event, that event triggers a POST / GET request on an external .php file which can save into a database or assign a $_SESSION var, but this is all done asynchronously, and quick, so the current PHP variables are still in effect :)
cheers
you can pass javascript variable like this
if (content != "")
{
var url = "your phpfile ?content="+content;
$.ajax({
url : url,
type: "post",
success:function(response)
{
document.getElementById("your field").innerHTML = response;
}
});
}
You can use Jquery to invoke a post request to a php page using AJAX and process it.
i want to pass a javascript string to php ... WHICH is RIGHT after the code .. in the script.
<script type="text/javascript">
var myvar = "mytext" ;
<?php echo myvar ; ?>
</script>
this does not work.
What should i do ?
When someone visits a website, this is generally what happens:
Their browser sends a request to the server.
The server evaluates that request.
The server realizes, "Egad, the page they're requesting has PHP!"
The server evaluates the PHP, and only sends the results to the browser.
The browser parses the content that it receives.
The browser realizes, "Egad, the page I received has JavaScript!"
The browser evaluates the JavaScript, entirely on the client's machine.
So PHP and JavaScript are basically at different ends of the process. Only the server handles PHP, and only the client handles JavaScript.
To "give" a string to PHP, you'd have to make a request of the PHP page, sending that string as a GET variable:
http://www.yourdomain.com/some_php_page.php?myvar=mytext
There are a few ways to do this with JavaScript.
If you only care about making that request on the PHP page, and you don't need to worry about receiving any information back, you can just create an image and use the URL as the source:
var fakeImg = new Image();
fakeImg.src = 'http://www.yourdomain.com/some_php_page.php?myvar=mytext';
Even though you're requesting an image, the server doesn't know that, and will process your request by calling the PHP evaluating it, etc.
You can make an actual AJAX request. Start by creating an XMLHttpRequest object:
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
There are some issues in IE with cached responses on AJAX requests, so make the url unique:
var url = 'http://www.yourdomain.com/some_php_page.php?myvar=mytext&unique=whatever';
Tell your XHR where you want it to go, and how you want it to get there:
xhr.open('GET', url, true);
// The "true" parameter tells it that we want this to be asynchronous
Set up a method that will check for when a response is received:
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status < 400) {
success(xhr.responseText);
}
};
And finally, send the request:
xhr.send(null);
// We set "null" because some browsers are pissy
Some notes to keep in mind:
You have to build the success function yourself, to handle the string that your PHP page will return.
You can pass that function xhr.responseXML if you want, but that's usually just a hassle for me.
Using onreadystatechange the way I have will (I believe) introduce memory leaks in some versions of IE
PHP is executed server side while javascript is client side, so that means that the PHP is already executed when you're sending your javascript code.
You might want to look into AJAX instead.
You should get the difference between client side and server side code clear. The variable you are introducing in the php code isn't assigned before because that variable is set at the client. So your code example is in essence wrong. If you want a value that is present at the client (javascript) to be available at the server (php), you need to do something with the xmlhttprequest object of javascript (also know as ajax).
You can do the other way around though...print a php value in javascript. This is because the script is than created server side and send to the client before it is being processed by the browser.
Not sure what you are trying to reach but maybe this helps a bit.
Your example is somewhat confusing:
<script type="text/javascript">
var myvar = "mytext" ;
<?php echo myvar ; ?>
</script>
Because if I do this:
<script type="text/javascript">
<?php $myvar = "mytext"; ?>
var myvar = "<?php echo $myvar; ?>" ;
</script>
Then it sets the JavaScript value of myvar to the PHP value of $myvar so they both stay the same. If you're trying to do something else you need to expand your example.
I have a javascript variable which holds some information and I want that to assign in a PHP variable. Here is what I am using:
<script type="text/javascript">
function redirectToFacebook()
{
var facebookMessage = encodeURI(document.getElementById('txt_msg').value);
}
</script>
<?php
$_SESSION['sess_facebook_message'] = facebookMessage;
?>
Any help is really appriciable.
Thanks in advance
Because PHP runs on the server, and JavaScript in the client, there is no way to set a PHP session variable after JavaScript works with it, as PHP has done executing before the page was even sent.
However...
If you use JavaScript to make a request (AJAX, imagehack or otherwise) to a PHP script that sets the variable, you can.
For example...
JavaScript:
function something() {
// do something with somevar
somevar = 'content';
// make an AJAX request to setvar.php?value=content
}
PHP:
$_SESSION['somevar'] = $_GET['somevar'];
Make sure you take security issues of client-generated data into account, though.
If you want to pass variables from the browser (javascript) to your backend server (PHP), you need to either:
1) Load a new page with Javascript parameters encoded either as POST or GET
2) Asynchronously call a PHP script (AJAX call) encoding the parameters as POST or GET
A simple example using a GET request (you simply append your parameters to the URL):
<script>
window.location = '/some-url?' + document.getElementById('text_msg').value;
</script>
You probably want to assign this piece of code to a button or something...
what you are trying to achieve is not possible due to API limitation.It does not provide that.
may be you can try to redirect with javascript and pass variables form php to js. They way yout tru it, it can't work.
may be, im realy not shure
try this.
<?php
function redirectToFacebook() {
var facebookMessage = ?>
<script>
document.write(encodeURI(document.getElementById('txt_msg').value));
</script>
<?php
}
?>
or using cookies.
For javascript there is an unload function, when a page closes, do something. Is there the same for php?
Thanks
Jean
PHP is server side, so by the time your user sees the page, the PHP thread is already done. You could of course put an ajax call in your javascript unload though that calls a PHP script.
PHP is a server-side technology. It has no idea that the page is closing unless you use JavaScript to send a message to a PHP script. Then it's just as any other php page.
If you want to execute something at the end of your request, you can use register_shutdown_function:
function my_func() {
// perform some cleanup
}
// my_func will be called after the rest of your script has executed
register_shutdown_function('my_func');
Since PHP is a server side language it's not possible to do something like this without using some sort of browser based scripting language.
short answer NO!
the reason for this is that PHP just creates a page, ones it has built up the page it sends the html to Apache to serve, when this is done, the PHP script is already finished.
A possible hack is using javascript.
so heres and example, Requires jQuery¬
$.fn.unloadping = function(url,params,callback)
{
this.onbeforeunload = function()
{
$.ajax({
type : 'GET',
data : params,
success : function(response)
{
callback(this) //Send window context back
}
});
return false;
}
return $(this); //keep the chain
}
and can use like so
$(window).unloadping('/ping/closewindow.php',{page:window.location.href},function(context){
this.close(); //Needs to be checked
});
can i ask why you would like to do this? what's your motives etc. ?
PHP is not event-oriented, the best way to know if a page finished is in the last line.
If you need to know when a class is "unloaded" you can use the function __destroy