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.
Related
i am passing variable from javascript php with the following code by using cookie.
<script type="text/javascript">
function gTest() {
var country = 'hello testing';
document.cookie = 'name=document.write(country);' ;
document.write(country);
}
gTest();
</script>
<?php
echo "<br>";
var_dump($_COOKIE['name']);
?>
it works fine if we change to
document.cookie = 'name=hello' ;
i want to pass variable value to php in same page...i don't want to send to another page.
thanks
$_COOKIE is populated with the data sent from the browser to the server.
The JS to change the cookie won't run until the response is sent back and the JavaScript is executed.
The values in $_COOKIE won't update until you make a new HTTP request.
You can use XHR.
JavaScript (using jQuery):
$.ajax('script.php', {
data: { 'name': 'hello' }
});
PHP:
var_dump($_GET['name']);
You cant.
Ok, I think I got to explain. On your page, there is the Javascript first, then the PHP code, but it doesnt execute in that order.
First the server execute the PHP code, send the page as HTML and the javascript is executed on the client side.
If you really dont want to reload the whole page, the only way to do it is to use an ajax request to a page where your PHP code is. Simply use JQuery and replace your PHP code with this :
$('#result').load('showCookie.php');
Content of showCookie.php will be your var_dump and the page will do exactly what you want, except that you have called an additional page with JQuery.
I want the value of JavaScript variable which i could access using PHP.
I am using the code below but it doesn't return value of that variable in PHP.
// set global variable in javascript
profile_viewer_uid = 1;
// php code
$profile_viewer_uid=$_POST['profile_viewer_uid'];
this gives me the following error :-
A PHP Error was encountered
Severity: Notice
Message: Undefined index: profile_viewer_uid
Another php code i used which give empty value
$profile_viewer_uid = "<script language=javascript>document.write(profile_viewer_uid);</script>
When I echo it shows nothing.
Add a cookie with the javascript variable you want to access.
document.cookie="profile_viewer_uid=1";
Then acces it in php via
$profile_viewer_uid = $_COOKIE['profile_viewer_uid'];
You will need to use JS to send the URL back with a variable in it such as:
http://www.site.com/index.php?uid=1
by using something like this in JS:
window.location.href=ā€¯index.php?uid=1";
Then in the PHP code use $_GET:
$somevar = $_GET["uid"]; //puts the uid varialbe into $somevar
Here is the Working example: Get javascript variable value on the same page.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
You might want to start by learning what Javascript and php are. Javascript is a client side script language running in the browser of the machine of the client connected to the webserver on which php runs. These languages can not communicate directly.
Depending on your goal you'll need to issue an AJAX get or post request to the server and return a json/xml/html/whatever response you need and inject the result back in the DOM structure of the site. I suggest Jquery, BackboneJS or any other JS framework for this. See the Jquery documentation for examples.
If you have to pass php data to JS on the same site you can echo the data as JS and turn your php data using json_encode() into JS.
<script type="text/javascript>
var foo = <?php echo json_encode($somePhpVar); ?>
</script>
If you want to use a js variable in a php script you MUST pass it within a HTTP request.
There are basically two ways:
Submitting or reloading the page (as per Chris answer).
Using AJAX, which is made exactly for communicating between a web page (js) and the server(php) without reloading/changing the page.
A basic example can be:
var profile_viewer_uid = 1;
$.ajax({
url: "serverScript.php",
method: "POST",
data: { "profile_viewer_uid": profile_viewer_uid }
})
And in the serverScript.php file, you can do:
$profile_viewer_uid = $_POST['profile_viewer_uid'];
echo($profile_viewer_uid);
// prints 1
Note: in this example I used jQuery AJAX, which is quicker to implement. You can do it in pure js as well.
PHP runs on the server. It outputs some text. Then it stops running.
The text is sent to the client (a browser). The browser then interprets the text as HTML and JavaScript.
If you want to get data from JavaScript to PHP then you need to make a new HTTP request and run a new (or the same) PHP script.
You can make an HTTP request from JavaScript by using a form or Ajax.
These are two different languages, that run at different time - you cannot interact with them like that.
PHP is executed on the server while the page loads. Once loaded, the JavaScript will execute on the clients machine in the browser.
In your html form make a hidden field
<input type="hidden" id="scanCode" name="SCANCODE"></input>
Then in your javascript update the field value by adding;
document.getElementById("scanCode").setAttribute('value', scanCode);
This could be a little tricky thing but the secure way is to set a javascript cookie, then picking it up by php cookie variable.Then Assign this php variable to an php session that will hold the data more securely than cookie.Then delete the cookie using javascript and redirect the page to itself.
Given that you have added an php command to catch the variable, you will get it.
You need to add this value to the form data that is submitted to the server. You can use
<input type="hidden" value="1" name="profile_viewer_uid" id="profile_viewer_uid">
inside your form tag.
I'd like to use the variable bradio in the "Having" clause of my query but i don't know how to get the content of the jquery variable and passe it into my sql query. This is a fragment of my php file. Can you tell me how can I do this?
Thanks
$conn = mysql_connect("localhost","form-test","pass");
$db = mysql_select_db("form-test",$conn);
?>
<script type="text/javascript">
jQuery.noConflict();
jQuery(function()
{
jQuery('#event_form_field-<?php echo $event_id; ?>').click(function()
{
var bradio= jQuery("input[type=radio]:checked").val()
alert(bradio); });});
</script>
<?php
$query2 = "SELECT COUNT(wp_events_answer.answer) as rep, wp_events_answer.attendee_id as idq, wp_events_question.quota as quota2, wp_events_attendee.event_id as ev, wp_events_answer.answer as answ, wp_events_question.id as qst3
FROM wp_events_answer, wp_events_attendee, wp_events_question
WHERE wp_events_answer.question_id = wp_events_question.id AND wp_events_answer.attendee_id = wp_events_attendee.id
HAVING answer =
GROUP BY answ;";
$result2 = mysql_query($query2) or die(mysql_error());
while($row2 = mysql_fetch_row($result2)) {
}
?>
You can't mix both PHP and javascript code in one page using the method above. The problem is because PHP is executed on the server, well before any javascript can be run on the client. Therefore, the two cannot speak to each other.
The solution here is to make an AJAX request to a PHP script on your server and pass the value of the radio control to it. This would then return the required data and you can then use javascript to display this on your page.
For example:
$.post(
'myScript.php',
'bradio=' + jQuery("input[type=radio]:checked").val(),
function(data) {
// process your result here
}
);
Write the query in another php file and pass the variable using an GET or POST or maybe ajax call
No you cannot pass a js variable to php in this way. The php code is executed before the page has sent to the browser while the js code is executed after: you need instead an ajax call with the bradiovalue passed along the request (get or post)
Either you need to send an POST Request and reload the page or you need to pass the variable via AJAX to the current page and change the output on the fly. Via jquery it's pretty simple to send an AJAX request via http://api.jquery.com/jQuery.ajax/
You will need to make a request from javascript ($.get or $.post) and pass value of this radio button as a parameter. Then, on PHP side you will be able to get it from $_GET or $_POST array.
Is there any way I could get the value of a html text field without using GET or POST or REQUEST? Alternatively, is there any way to get the field value in the same form or page else where.
This works with direct value such as "james", "system" and so on. the only problem is how do i make it work with html field values
Like:
<input type = "submit" onclick = "
<?php $username = "kut";
$result = checkname($username);
if($result)
{
?> alert("success"); <?php
}
else {?> alert("failed"); <?php
}?>
">
How can i replace "kut" with the value of a text field with id = "username" ?
<?php $username = "?>document.getElementById('username').value;<?php"?>
or something like that...???
In short, I need to get the value of a html field else where in the same page inside a javascript function, using PHP... like in the above javascriptFunction(), function
You have fundamental misunderstanding of how client-server architecture works.
PHP can be executed thousands of miles away, even days apart, from place where and when JavaScript does.
First PHP generates whole page, all of HTML, all of JavaScript source code (unexecuted), and then, after PHP is done and gone, browser starts running JavaScript.
These two can't be mixed together like you wanted, even though it may seem so in the PHP source code.
Although you can communicate with the server again using AJAX or similar, you probably should first understand how client-server architecture works and try to solve the problem without AJAX (e.g. handle all of it on server side, or all on client side).
You can not directly call a PHP function in JavaScript. You could set a JavaScript value from php before the page loads via echo. PHP is executed on the server while JavaScript is executed on the client side.
1> I suggest using jQuery to handle the Ajax part.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function check_user(){
var user_el=document.getElementById('username');
if(!user_el){ return false; }
var username=user_el.value; // this could all be replaced with $('username').val()
$.getJSON('check_var.php',{"user":username},function(data){
if(data.result=='error'){ alert('something was wrong with the PHP stuff'); }
alert(data.userstatus);
});
}
</script>
2> On the PHP side, as check_var.php, you need a script that takes the username input, checks the DB, and sends back the result as JSON data.
<?php
if(!isset($_GET['user']){ exit; }
$username=preg_replace('#['^\w\d]#','',$_POST['user']);
//do your database query. I assume you have that part all set.
//since I'm not filling in all of that, you'll need to fix this next part to work with your system
//let's pretend it's like $found=check_user($username);
//be sure to use mysql_real_escape_string or prepared statements on the $username var since you're working with user input
$status=$some_db_error ? 'error' : 'success';
$results=array('result'=>$status,'userstatus'=>$found);
header('Content-Type: application/json');
echo json_encode($results);
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.