I have a page that has a javascript date picker, the result of which goes into an input box on an HTML form (see image below). This works fine.
I would also like the chosen date to be stored in as session variable. Can anyone point to how I should do this? Can a session variable be assigned within javascript?
Code so far:
<?php
session_start();
Datepicker
....
<script type="text/javascript">
window.onload = function(){
g_globalObject1 = new JsDatePick({
useMode:2,
target:"inputFieldStart",
dateFormat:"%Y-%m-%d",
cellColorScheme:"armygreen"
});
};
</script>
HTML Form
<form action="https://website" method="Post">
<input name="StartDate" type="text" id="inputFieldStart">
<input type="Submit" value="Update" class="button">
</form>
The session variable needs to be set as a php variable, on the server. Your HTML form, which calls your server with a Post method passes this variable to the php page, and it can be read and set as a session variable using
<?php
$start_date = $_POST["StartDate"];
$_SESSION['start_date'] = $start_date;
?>
Set it to session with
$_SESSION["date"] = $_POST["StartDate"];
to "set it with javascript" use AJAX. For instance jQuery's $.ajax
A session variable cannot be assigned with JavaScript directly, you can however use AJAX to send a request to a PHP document to create/change the session variable if you must insist on using JavaScript.
In your PHP document (we'll call it date_assign.php) write the following:
$date = $_POST['date'];
$_SESSION['date'] = $date;
Then in your JavaScript use this function (with the jQuery library included, of course) to send the request to the PHP document.
// Function to call in order to change session variable.
function sessionVariable() {
// Get date from picker.
var date = $('#inputFieldStart').value();
// Create data string.
var datastr = 'date=' + date;
// Create the AJAX request.
$.ajax({
type: 'POST',
url: 'date_assign.php',
data: datastr
});
}
Of course this is a long way around of doing it but it means you can accomplish it with JavaScript. You can call the function whenever you need to set the session variable, this can be done on an interval or you can bind a click listener to the Submit button to send the data, your call.
Related
I have a variable $count = 10;that I want to increase by 10 each time a user clicks <a id="load-more" href="#">Load more</a>
I have tried setting this up with onclick, variable equations and functions but I cannot seem to get it to increase.
Ultimately, I want the $count = 10; to increase to $count = 20; and so forth each time the user clicks.
Any help is appreciated.
If I understand your question properly, you're looking for a solution that makes use of AJAX. Something like this:
On the client:
$('#load-more').click(function () {
$.ajax({
type: 'POST',
url: "http://example.com/stuff.php",
async: true,
success: function(data) {
// Success! Do something with `data` here:
},
error: function (jqXHR, textStatus, errorThrown) {
// Error! You should probably display an error message here:
}
})
})
On the server (stuff.php):
<?php
$value = retrieveValue(); // Replace this with whatever means you are using to get the persisted value.
$value += 10; // Increment the value by 10 each time.
saveValue($value); // Replace this with whatever means you are using to save the persisted value.
?>
Keep in mind that in order to keep the value incrementing with each request you will have to persist the value in PHP by some means (database, session, file, etc.).
You will also need to load JQuery libs in your HTML file to use the above JavaScript code.
It's not possible to change PHP variable's value (server side) by JavaScript (client side).
You can define a JavaScript variable and initialize it using PHP. But after that you can work only with your JavaScript variable.
<script>
var jsVar = <?php echo $phpVar; ?>;
jsVar++;
</script>
This is the way. For more information, the above code is sending PHP variable value to JavaScript(and the conversely is not possible).
You can also send a JavaScript variable's value to a PHP script using AJAX commands.
And if you want to use AJAX command, you can do it via pure JavaScript or using jQuery or other libraries. jQuery usage is easier but you need to load the library. I do prefer pure JavaScript AJAX. Here is an example:
<script>
var xhr = new XMLHttpRequest();
xhr.open('POST', 'php_script.php');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
// do something
}
};
xhr.send('value=' + jsVar);
</script>
And you can use value as $_POST['value'] in php_script.php file.
Here it is.
<input type="number" value="10" id="data">
<a id="load-more" href="#" onClick="increment()">Load more</a>
<script>
function increment(){
var count = parseInt(document.getElementById("data").value);
count = count+=10;
document.getElementById("data").value = count
$.post('backend.php?count='+$("#data").val(),function(val){//alert});
}
</script>
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 3 years ago.
First I thought that I had to convert JavaScript to PHP, but then I found out that I cannot because of server and client side executions. So now I simply want to send ONE variable
<script type="text/javascript">
function scriptvariable()
{
var theContents = "the variable";
}
</script>
to a PHP variable
<?php
$phpvariable
?>
That function in the JavaScript executes when let's say I click on a button.
Now I have no idea on how to assign that phpvariable to the JavaScript one to use the phpvariable to look up stuff in my database. I know I can add it to my url or some thing and refresh the page, but I would like to do it with AJAX as I might have to use this Ajax method further in my webpage.
So is there an easy way to do this without having to dump pages of code on my page to do one simple thing?
PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:
<script type="text/javascript">
var foo = '<?php echo $foo ?>';
</script>
To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):
var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});
On your server, you would need to receive the variable sent in the post:
$variable = $_POST['variable'];
As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post
Maybe the most easiest approach for you is something like this
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
On your myphpfile.php you can use $_GET['name'] after your javascript was executed.
It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.
In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :
http://www.somesite.com/send.php?variableName=someValue
or
http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue
This way, from PHP you can access this value as:
$phpVariableName = $_POST["variableName"];
for forms using POST method or:
$phpVariableName = $_GET["variableName"];
for forms using GET method or the append to url method I've mentioned above (querystring).
By using below code on button click I get the href attribute value, until this everything is fine but when I got my href link on button click we want to store it in the session variable (i.e. var href) because we also use this variable elsewhere. Please suggest me how to store JavaScript variable in session.?
<script>
$(document).ready(function(){
$('.button').click(function(){
var href = $(this).val();
alert(href);
})
});
</script>
<button value="<?php echo $value['3']; ?>" class="button" style="background-color:#ff8c21;">Buy Now</button>
You can't set SESSION WITH JAVASCRIPT this is because its server side functionality so if you want to use this data some where else you can send a ajax request to server and there you can create session for this data.
JS:
$(document).ready(function(){
$('.button').click(function(){
var href = $(this).val();
$.ajax({
type: "POST",
url: url,//url to file
data: {val:href},
success: function(data){
//success
};
});
});
});
PHP:
session_start();
if(isset($_POST['val']))
{
$_SESSION['href'] = $_POST['val'];//created a session named "href"
}
//use session
if(isset($_SESSION['href']))
{
echo $_SESSION['href'];//use your session.
}
Please try it if you want to use session using jquery
First include jquery-1.9.1.js and jquery.session.js
$(document).ready(function(){
$('.button').click(function(){
var href = $(this).val();
$.session.set("yoursessioname", "storevalue");
})
});
alert($.session.get("yoursessioname"));
more detail http://phprocks.letsnurture.com/create-session-with-jquery/
If you want to store it in session which is SERVER side then you need use ajax pass variable and store it in php for example with
<?php
session_start();
!isset($_POST['var']) ?: $_SESSION['var'] = $_POST['var'];
but you can think of using cookies as well, then you don't need PHP it can be done only with JavaScript. There is nice Jquery plugin for that
JavaScript works in the browser and PHP sessions are activated on the server, so you can't change session variables without sending a request to the server eg via a url or by submitting a form.
BUT you could use sessionStorage, which is a similar principle but lives in the browser and is modifiable by javascript.
eg. (inside javascript)
sessionStorage.myvariable=myVal
etc. It will live as long as your tab is open (from page to page).
This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 3 years ago.
First I thought that I had to convert JavaScript to PHP, but then I found out that I cannot because of server and client side executions. So now I simply want to send ONE variable
<script type="text/javascript">
function scriptvariable()
{
var theContents = "the variable";
}
</script>
to a PHP variable
<?php
$phpvariable
?>
That function in the JavaScript executes when let's say I click on a button.
Now I have no idea on how to assign that phpvariable to the JavaScript one to use the phpvariable to look up stuff in my database. I know I can add it to my url or some thing and refresh the page, but I would like to do it with AJAX as I might have to use this Ajax method further in my webpage.
So is there an easy way to do this without having to dump pages of code on my page to do one simple thing?
PHP runs on the server and Javascript runs on the client, so you can't set a PHP variable to equal a Javascript variable without sending the value to the server. You can, however, set a Javascript variable to equal a PHP variable:
<script type="text/javascript">
var foo = '<?php echo $foo ?>';
</script>
To send a Javascript value to PHP you'd need to use AJAX. With jQuery, it would look something like this (most basic example possible):
var variableToSend = 'foo';
$.post('file.php', {variable: variableToSend});
On your server, you would need to receive the variable sent in the post:
$variable = $_POST['variable'];
As Jordan already said you have to post back the javascript variable to your server before the server can handle the value. To do this you can either program a javascript function that submits a form - or you can use ajax / jquery. jQuery.post
Maybe the most easiest approach for you is something like this
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
On your myphpfile.php you can use $_GET['name'] after your javascript was executed.
It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.
In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :
http://www.somesite.com/send.php?variableName=someValue
or
http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue
This way, from PHP you can access this value as:
$phpVariableName = $_POST["variableName"];
for forms using POST method or:
$phpVariableName = $_GET["variableName"];
for forms using GET method or the append to url method I've mentioned above (querystring).
I want to know whether I can retrieve data from database in .js file using php code written in same .js file. I have a passwordvalidation.js file. In that file, by using onblur event or onclick event, I want to compare the password values with the stored value in password. Now I have password verification code in php and I can compare passwords using that function. But I want to compare it while user entering new password in field. And I want to write ajax and php code in same .js file. But I don't know how to achieve that. Please help on this. Thank you.
use jquery
$.ajax({
url: 'test.php',
success: function(data) {
$('.result').html(data);
}
});
If you want to use any value which is assigned to any PHP variable, use a hidden input type, set php variable in it and call the value from js function
<input type="hidden" id="my_value" value="<?php echo $myvar; ?>" />
In js function
var phpval = document.getElementById("my_value").value;
Now you can retrive the PHP variable value inside JS function ( var phpval)