i want to pass a javascript string to php ... WHICH is RIGHT after the code .. in the script.
When someone visits a website, this is generally what happens:
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:
success
function yourself, to handle the string that your PHP page will return.xhr.responseXML
if you want, but that's usually just a hassle for me.onreadystatechange
the way I have will (I believe) introduce memory leaks in some versions of IE