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).
Related
I can pass data with this url code to my second php file.
www.test.com/second.php?task=demo&id=55
and I can pass data with this javascript code
<script>
$(function(){
var postdata= 'task=demo&id=55';
$.ajax({
type:'GET',
url:'second.php',
data:postdata,
});
});
</script>
I want to pass this data task=demo&id=55 with php, How can I do that? Thank you.
I can do this with form but I have to do this automatically after page loaded
second.php
$task = $_GET["task"];
$id = $_GET["id"];
...
...
...
other codes
There are several ways to pass values. If second.php is not executed by the same environment, then you can send the values using cURL.
If you intend to redirect to the second page, then you can redirect to second.php using this command:
$youridvalue = 55;
$task = "demo";
header('Location: http://www.test.com/second.php?task='.$task.'&id='.$youridvalue);
If you intend to execute second.php, but to stay on first.php, then you can set the $_GET values, like this:
$_GET['task'] = 'demo';
$_GET['id'] = '55';
and then require or include second.php. However, in this case it is recommended to separate the functionality from second.php into a class or function, so you can reuse the functionality without the need to include or require second.php and/or duplicate your code on multiple places.
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>
After hours of playing with this, it hit me that my JQuery simply isn't executing.
I have a page that I am trying to submit to a PHP script without refreshing/leaving the page. If I use a typical form action/method/submit, it inserts into my database just fine. But when I use JQuery, the JQuery will not run at all. The alert does not show. (I'm new to JQuery). I have tried to research this, but nothing is working.
Here is my main page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('submitpicks').on('submit','#submitpicks',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
</script>
</head>
<body>
<form name="submitpicks" id="submitpicks" action="" method="post">
<script language="javascript">
var v=0;
function acceptpick(thepick,removepick){
var userPick = confirm("You picked " + thepick + ". Accept this pick?");
//var theid = "finalpick" + v;
var removebtn = "btn" + removepick;
//alert(theid);
if(userPick==1){
document.getElementById("finalpick").value=removepick;
document.getElementById(removebtn).disabled = true;
document.getElementById("submitpicks").submit();
v=v+1;
}
}
</script>
<?php
include "Connections/myconn.php";
//$setid = $_SESSION["gbsid"];
$setid = 11;
$setqry = "Select * from grabBagParticipants where gbsid = $setid order by rand()";
$setresult = mysqli_query($conn, $setqry);
$u=0;
if(mysqli_num_rows($setresult)>0){
while($setrow = mysqli_fetch_array($setresult)){
//shuffle($setrow);
echo '<input type="button" name="' . $setrow["gbpid"] . '" id="btn' . $setrow["gbpid"] . '" value="' . $u . '" onClick=\'acceptpick("' . $setrow["gbpname"] . '", ' . $setrow["gbpid"] . ');\' /><br />';
$u=$u+1;
}
}
?>
<input type="text" name="finalpick" id="finalpick" />
<input type="submit" value="Save" />
</form>
<div id="results"> </div>
</body>
</html>
Here is my PHP:
<?php
include "Connections/myconn.php";
$theGiver = 1;
$theReceiver = $_POST['finalpick'];
$insertsql = "insert into grabBagFinalList(gbflgid, gbflrid) values($theGiver, $theReceiver)";
mysqli_query($conn, $insertsql);
?>
you can use e.preventDefault(); or return false;
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault();
$.post('submitpick.php', $(this).serialize(), function(data) {
$('#results').html(data);
});
// return false;
});
});
</script>
Note: in your php you not echo out anything to get it back as a data .. so basic knowledge when you trying to use $.post or $.get or $.ajax .. to check the connection between js and php .. so in php
<?php
echo 'File connected';
?>
and then alert(data) in js .. if everything works fine .. go to next step
Explain each Step..
before everything you should check you install jquery if you use
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
from w3schools website.. its totally wrong .. you should looking for how to install jquery ... then
1st to submit form with js and prevent reloading.. and you used <script> in your main page
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
<script>
output : alert with Form submitted Without Reloading ... if this step is good and you get the alert .. go to next step
2nd add $.post to your code
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
$.post('submitpick.php', $(this).serialize(), function(data){
alert(data);
});
});
});
<script>
and in submitpick.php >>> be sure your mainpage.php and submitpick.php in the same directory
<?php
echo 'File connected';
?>
output: alert with File connected
Have you heard of AJAX(asynchronous javascript and XML). While it may not be something that is easy to learn for someone who is new to JQuery and javascript, it does pretty much what you need. Well, its a bit more complicated than that, but basically AJAX submits information by using HTTP requests (much like normal forms) but without refreshing the page.
Here's a link to a tutorial: http://www.w3schools.com/ajax/ with vanilla javascript.
Here's one with Jquery: http://www.w3schools.com/jquery/jquery_ajax_intro.asp
And here's an example of how you can set it up with Jquery:
$(document).ready(function() {
$.ajax({
method: "POST",
url: "/something.php"
dataType: "JSON",
data: {formData:{formfield1: $('formfield1').val(), formfield2: $('formfield2)'.val()}},
success: function(data){
if (data["somevalue"]) == something {
dosomething;
} else {
dosomethingelse
},
error: function() {
alert("Error message");
}
});
});
This is only a basic example, now what does all this stuff mean anyway. Well, there are several methods, some of them are POST and GET, these are HTTP request methods, which you can use to do several things. I'm no expert on this stuff, but here's what they do:
Method
POST
POST basically works, to submit information to a server, which is then usually inserted to a database to which that server is connected to. I believe most forms utilize POST requests, but don't quote me on that.
GET
GET on the other hand requests data from a server, which then fetches it into the database and sends it back to the client so it can perform an action. For instance, whenever you load a page, GET requests are made to load the various elements of a page. What's important to note here, is that this request is made specifically to retrieve data.
There are other types of HTTP requests you can use such as PUT and DELETE, which I'd say are the most common along with GET and POST. Anyway I'd recommend that you look them up, its useful information.
Url
The url represents the path to which you are making a request, I'm not exactly sure how it works with PHP, I think you just need to call the PHP page in question and it will work properly, but I'm not sure, I haven't used PHP since my last semester, been using Rails and it doesn't work quite the same. Anyway, lets say you have some PHP page called, "Something.php" and lets say that somethihng PHP has the following content:
<?php
$form_data = $_POST['data'];
$array = json_decode(form_data, true);
do something with your data;
$jsonToSendBack = "{status: 1}";
$response = json_encode($jsonToSendBack);
echo $response;
?>
So basically what that file received was a JSON, which was our specified datatype and in turn after we finish interpreting data in the server, we send back a response through echo our echo. Now since our datatype is a JSON, the client is expecting a response with JSON, but we'll get to that later. If you're not familiar with JSON, you should look it up, but in simple terms JSON is a data exchange format that different languages can utilize to pass data to each other, like in this example, where I sent data to PHP through Javascript and vice-versa.
DataType
Data type is basically, the type of information that you want to send to the server, you can specify it through ajax. There are many data types you can send and receive, for instance if you wanted to, you could send XML or Text to the server, and in turn it should return XML or text, depending on what you chose.
Success and Error
Finally, there's the success and error parameters, basically if a request was successful, it returns a status code of 200, though that doesn't mean that other status codes do not indicate success too, nonetheless 200 is probably the one you'd like to see when making HTTP requests. Anyway, success basically specifies that if the request succeeded it should execute that function code I wrote, otherwise if there is an error, it will execute the function within error. Finally, even if you do have a success on your request, that doesn't mean everything went right, it just means that the client was successful in contacting the server and that it received a response. A request might be successful but that doesn't generally mean that your server-side code executed everything perfectly.
Anyway, I hope my explanation is sufficient, and that you can take it from here.
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.
I need to save the value of a input type text in a PHP variable as soon as the user writes it. I found that the blur event in JQuery can trigger an event that happens after writing to the input type text, so I have the following:
<script>
$("document").ready( function()
{
$("#primerApellido").blur(function() {
alert('out');
<?php
$primerApellidoForm =
"<script type=\'text/javascript\'>
$('#primerApellido').val();
</script>
";
?>
});
});
</script>
And here is my input type text:
<input type="text" id="primerApellido" name="primerApellido" value="<?php echo $primerApellidoForm?>"/>
So as you can see, I need to save what is typed on the input on the PHP variable as soon as the user leave the text box. Right now it save literally the Javascript variable assignation, not the value that I need.
How can I assing the typed value on the text box to my PHP variable?
I think you may be confusing PHP and Javascript a bit.
PHP only runs on the server.
Javascript only runs on the browsers.
You cannot modify PHP variables from javascript directly.
What you can do however, is make an ajax call to another page to do something with that variable such as save it in the session or into a database.
Check out the Javascript jQuery ajax command. With this command you can run another page without leaving the one you are currently on. You can have that page be a PHP page that receives the variable and performs an action with it.
Try this..
$("#primerApellido").onkeyup(function() {
var user_input = $(this).val();
$.ajax({
type:'GET',
url: 'path/to/your/phppage',
data:{user_input:user_input},
success: function(response) {
//alert(response);
}
});
});
I followed the advice from Mark Carpenter to use Ajax function, below is the code that do what I want:
$("document").ready( function()
$("#primerApellido").blur(function() {
$.ajax({
type: "GET",
url: "destinationURL.php",
data: "primerApellidoForm="+$('#primerApellido').val(),
success: function(msg){
alert( "Data Saved: "+msg);
}
});
});
});
Now the PHP variable "primerApellidoForm" have the value from $('#primerApellido').val() input type.
Not sure what you are trying to do is possible. Once you have loaded the page, there is no way you can run the php code ( You can make ajax requests though ) . Hope the following helps.
How can I use a JavaScript variable as a PHP variable?
you can try this...
<script type="text/javascript">
$("#primerApellido").blur(function() {
<?php $primerApellidoForm = "<script>document.write($(this).val());</script>"?>
});
</script>