I'm working in PHP and I added the following jQuery code to display the current year:
<script src="http://code.jquery.com/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="/script/jquery-1.4.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var currentYear = (new Date).getFullYear();
$(document).ready(function() {
$("#year").text( (new Date).getFullYear() );
});
</script>
<p><span id="year"/></p>
(this code works perfectly: when displaying the page I can see 2015)
What I now want is to put this current year into a PHP variable (like $currentYear), so I will be able to use it in PHP for operations like this one:
$purchaseYear = 1985;
$yearsLivedOld = $currentYear-$purchaseYear;
How to put the year in a PHP variable ?
It's not possible in the way you're trying to do it. Javascript (and thus JQuery) work on the client machine, after the page was sent and the connection with server closed. To get data from client machine your best bet would be an AJAX call which opens a new connection to the server and allows you to load (and send) additional data between the client and the server.
Whole AJAX tutorial is out of scope here, but maybe this link will help you.
If you only want the current year though, you can skip the javascript and do it in PHP, like so:
$purchaseYear = date("Y");
PHP is rendered server side and javascript is rendered client side.
So in a way you can say that PHP is rendered before javascript, which means that you can assign a PHP variable to a javascript variable but cannot do vice-versa.
Therefore you can choose either of the solutions provided by aldrin27 or Till Helge.
Either use
1. AJAX to pass the data generated by javascript to server so that PHP can render it.
2. You can directly get current date in PHP using date('Y'); so there is no need of javascript for this piece of code.
you can use ajax to pass the variable to your php script
var year = $("#year").text();
$.post("your_script.php", {year: year});
and after that you can use the variable in your php script
<?php
$year = $_POST['year'];
echo $year;
?>
you can learn more about ajax in here
Use the jQuery AJAX function (or the post shorthand function).
Javascript:
$.ajax({
url: 'path/to/myscript.php',
type: 'POST',
data: 'current_year=' + currentYear,
success: function(data) {
//Optional callback function on success
}
});
PHP:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['current_year'])) {
//Should really validate/sanitise data here
$currentYear = $_POST['current_year'];
}
}
You could also send it via an HTML post, although that would require a page reload, so AJAX would be more preferable.
Related
Is there any way to do it without doing this:
send javaScript variable to php variable
OR can I do that, and "cover up" my url to the original one, without refreshing the page(still keep the php variables)?
I believe you are incorrect - you actually DO get the 'javascript' variable to PHP - using the jQuery code snippet below by #MikeD (jQuery is a javascript library containing many and many functions that you can then use in your code - making things little easier to do) above you can pass the javascript variable to PHP page.
On the php page you can assign this variable (originating on client side - browser) to PHP variable using something as simple as this:
$variable = $_REQUEST['javascriptVariable'];
A nice and easy way to do this is like this:
PHP
<div id="something" data-info="<?php echo $info ?>"></div>
Jquery
var info = $("#something").data("info");
EXPLANATION
Put the variable as a data attribute in some div using PHP, and then grab the data attribute from the DOM using JQuery.
There's two points that you can use PHP to create javascript vars, the first being when the "page" is created on the server, the second point is during the operation of the javascript application (once the page is loaded). The second point will require some sort of client side request (ajax, websocket, etc).
The best way to do it (in my experience) is using PHP's json extension which allows you to encode a PHP object/array into a json serialized string that can be unserialized/decoded within the browser into equivalent javascript types.
To do this during page generation can be done similarly as follows:
echo "jsvar = eval('('+".json_encode($phpvar)."+')')";
Note that the eval occurs on client side within browser and is common in every major js library.
Requesting an object during the normal operation of your javascript app will vary depending on how the data is requested, but each way will involve an asynchronous javascript request, a PHP script to handle the request (on the server side), and then a javascript side handler/callback that is called when data is received within javascript as a response to the request.
I typically use PHP to echo a json_encode()'ed string as plain text, then code the javascript side response callback to decode the response and fire an event. For a basic example:
PHP side:
<?php echo json_encode($responce_object); // DONE ?>
javascript side:
on_responce(responce)
{
var res_obj = eval('('+responce+')');
fire_event(res_obj);
}
The example above is very simple and generic to show how it works, but not much more is required for a fully functional solution. The real magic for a specific solution will happen within the "fire_event()" method - this is where the object can be handled via jquery or whatever.
You would want to wrap a lot of security around this code before putting it anywhere you care about, but it illustrates the principles without putting too much mud in the water:
<head>
<script>
function loadDiv(url)
{
$('#YourDivID').load(url);
}
</script>
<body>
<?php
$thisID = 1; //set here for demonstrative purposes. In the code this was stolen from, a MS SQL database provides the data
$thisGroup = "MyGroup";
$thisMembers = "TheMembers";
$thisName = "Just a example";
echo "<button onclick=loadDiv('http://siteonyourdomain.com/yourpage.php?ID=$thisID&group=$thisGroup&members=$thisMembers');>$thisName</button>";
//note this only works for sites on the same domain. You cannot load google.com into a div from yoursite.tv
//yourpage.php would have some code like this
// if(isset($_GET['thisID'])) {$myID = $_GET['thisID']} else {$myID = NULL}
?>
<div id="YourDivID">
Before
</div>
<?php
//I tested this code before posting, then replaced the domain and page name for security's sake
If you use $.ajax to make the submission to php you won't need to refresh the page. The code for the example on that page would look like this
var javascriptVariable = "John";
$.ajax({
url: '/myphpfile.php',
type: "GET",
dataType: "json",
data: {
name: javascriptVariable,
},
success: function( data ) {
// do success function here
},
error:function( xhr, ajaxOptions, thrownError ) {
// handle errors here
}
}, "json");
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"];
?>
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.
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()}
});
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.