Passing a Javascript string to PHP - php

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.

Related

How to send variables from javascript to PHP

I want to know how to send variables from javascript to php so i can create a variable that contains dynamic sum of rows.
More specific:
When I search in my search box, i want to get the number of rows (1 match is 1 row, 2 matches is 2 rows and so on
I tried to implement this: document.getElementById("i1").value = allCells.length; so i later could call in the php, but i did not work.
This is my javascript, by the way the javascript works perfectly.
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$('#search').keyup(function() {
searchTable($(this).val());
});
});
function searchTable(inputVal)
{
var table = $('.table');
table.find('tr').each(function(index, row)
{
var allCells = $(row).find('td');
if (allCells.length > 0) {
var found = false;
allCells.each(function(index, td)
{
var regExp = new RegExp(inputVal, 'i');
if (regExp.test($(td).text()))
{
found = true;
return false;
document.getElementById("i1").value = allCells.length;
}
});
if (found == true)
$(row).show();
else
$(row).hide();
}
});
}
$(function()
{
$('#table a').click(function(e)
{
e.preventDefault();
$('#result').val($(this).closest('tr').find('td:first').text());
});
});
</script>
I wanted to spit the dynamicelly sum of rows her in my table header.
<h3>Total: (<?php print_r($_GET["i1"])?>) </h3>
I hope you can help me.
You probably have never learned the difference between javascript and php
Javascript is clientsided, which means everything is processed by your local system. PHP is server sided which means everything is processed by the server and parsed into html.
You can't send a value from javascript into plain php like you did.
You can however send a post or get to the same script and let that reload a part of your script
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.post/
You're not the first to want this, and not the first to be told it is impossible the way you imagine. When you browse to a PHP page things go basically like this:
Browser sends HTTP request to server
Server determines what page to send to the browser
Server discovers you want a PHP page
Server executes PHP
Server sends what is returned by PHP to the browser
Browser doesn't know about the PHP and displays HTML
Browser executes Javascript.
Now the important part is that the browser doesn't know what PHP is, but can execute JavaScript, while the server doesn't know what JavaScript is (for simplicity's sake) but can execute PHP. Bottomline: it is hard to communicate between the two because they are executed in different places. You'll most probably want to use AJAX, so here is a supersimple sample:
The PHP page we're going to fetch:
<?
// We're on the server
// We're going to output something:
echo "Yay! You can see me!"; // So the browser sees only "Yay! You can see me!" (without quotes).
?>
JavaScript (with jQuery) to fetch the PHP page:
$("#anElementID").load("thePHPPageWeWantToFetch.php"); // It's that simple! The element with the ID #anElementID now contains "Yay! You can see me!" (without quotes).
I suggest too, use AJAX or something to pass your javascript values to PHP.
You can create a AJAX call, add the data from your javascript, and catch the data in your PHP file.
var value = "Jan";
$.ajax({
url: "/form.php",
type: "post",
data: "name=" + value
});
in your PHP file you can do:
<?php
$catchedName = $_POST["name"];
?>

Pass Javascript var into PHP var

var javascript_variable = $("#ctl00").text();
<?php $php_variable = ?> document.write(javascript_variable); <? ; ?>
I want to pass the above javascript_variable into php_variable. This code is giving me an error. Any ideas on how?
You cannot do that.
PHP is executed on your server. Javascript on the otherhand is executed on your client's machine in the browser.
There are two different execution context. While you can pass a PHP variable into Javascript, you cannot do the opposite since PHP is executed first and the JavaScript code is the output of your PHP code.
If you want to send a Javascript variable to PHP, you have to do with in a separate request either via a cookie or an AJAX request. Here's an example:
$.ajax({
url: 'receivingScript.php',
data: {'value': $("#ct100").text()}
});

How do I assign a javascript variable to a PHP variable?

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.

How to activate PHP file in JavaScript function

I am trying to write some information into my database when I activate a javascript function.
I use PHP and MySQL. How can I open the .php file, execute it and return to .js file in order the function to continue its operation?
Thanks in advance.
I think you may be a bit confused. Javascript runs in the browser, on the client's computer. Php/MySQL runs on the server, responds to HTTP requests, and creates the content for the browser to display/run.
In order to get the two to communicate dynamically, you need to look at how to send/receive HTTP requests from javascript on the client to your php script on the server. You'll also need to be able to process responses in javascript. This practice is known as AJAX. The simplest way to do this is in my experience to use JSON and jQuery, http://api.jquery.com/jQuery.getJSON/
First of all, it is not possible to call PHP functions directly from JavaScript, or vice versa. This is because PHP is a server-side script, running on the server, and JavaScript is a client-side script, running on the browser.
But there is a solution, however, using a technique called "AJAX" (Asynchronous JavaScript and XML), which can be used to send a request to a server from JavaScript.
For instance, using a "user" page that the user sees, and a "request" page that is called from the JavaScript code, I could write the following code:
userpage.php:
<!-- JavaScript code -->
<script type="text/javascript">
function sendRequestToServer()
{
// The XMLHttpRequest object is used to make AJAX requests
var ajax = new XMLHttpRequest();
// The onreadystatechange function will be called when the request state changes
ajax.onreadystatechange = function()
{
// If ajax.readyState is 4, then the connection was successful
// If ajax.status (the HTTP return code) is 200, the request was successful
if(ajax.readyState == 4 && ajax.status == 200)
{
// Use ajax.responseText to get the raw response from the server
alert(ajax.responeText);
}
}
// Open the connection with the open() method
// (the third parameter is for "asynchronous" requests, meaning that
// JavaScript won't pause while the request is processing).
ajax.open('get', 'requestpage.php', true);
// Send the request using the send() method
ajax.send();
}
</script>
<!-- HTML code -->
<button onclick="sendRequestToServer();">Send request!</button>
requestpage.php (the output of this page will be returned to your JavaScript code):
<?php
echo "Hello World!";
?>
This example would, when the button is pressed, send a HTTP request to the server requesting requestpage.php, where the server would execute some server-side code and echo the result. The browser would then take the data it received from the server and use it in the script - in this case, alert() it.
Some resources:
AJAX wikipedia page
AJAX tutorials on Mozilla Developer Center and w3schools.com.
You might also want to check out JSON encoding, which is very common method of sending objects and arrays between clients and servers (especially when using AJAX):
JSON tutorial on MDC
json_encode() and json_decoder() PHP functions
(Sorry for such a long answer, hope it helped though)
You will need AJAX, there http://www.ajaxf1.com/tutorial/ajax-php.html a simple tutorial for AJAX using PHP server
look up AJAX... also think about using jQuery it has a simple and easy to use ajax() function.
If you're not already using an AJAX enabled framework (e.g. jQuery), you could just use a really lightweight XHR implementation to make a HTTP request. This request could have any PHP resource (performing the desired DB updates) as destination.
The smallest code I know of is found here: http://dengodekode.dk/artikler/ajax/xmlhttprequest_wrapper.php (Danish, sorry)
<script type="text/JavaScript">(function(){if(window.XMLHttpRequest)return;var o=null,s,
a=["MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0","Msxml2.XMLHTTP","Microsoft.XMLHTTP"];
for(var i=0,j=a.length;i<j;s=a[i],i++){try{if(o=new ActiveXObject(s))break}
catch(e){}}window.XMLHttpRequest=o?function(){return new ActiveXObject(s)}:null;o=null})()</script>
And the request:
var oHttp = new XMLHttpRequest();
oHttp.open("post", "http://www.domain.dk/page.php", true);
oHttp.onreadystatechange = function(){ myCallBack(oHttp) };
oHttp.send("id=123&noget=andet");

[PHP/JavaScript]: Call PHP file through JavaScript code with argument

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.

Categories