change session variable when clicking on link - javascript

This is an extension of the question here - Create a new page for different php ORDER BY statement?
I basically need to change a session variable and refresh the page at the same time using php (I think).
I.e. When I click <a href="#">Sort by date<a> on my page the following things happen:
$_SESSION['orderby']; = 'date';
Page refreshes
The session variable will then be changed and used later in my code.
I may need to use javascript? I'm not really sure, how would I do this?
EDIT
I do NOT want/need to be redirected to another page, the page just needs to be refreshed. Basically I need to click on a link (or button) and a php variable needs to be changed.
AJAX maybe?

What you would be able to do, is appending a GET-value to the URL and fetch that with PHP.
For instance:
<!-- HTML -->
Sort by <a href='?sort=date'>date</a>
// PHP:
if (isset($_GET['sort'])) {
$_SESSION['orderby'] = $_GET['sort'];
}
Additionally you can check if the GET-value is in a given array (to avoid errors from url-manipulation):
if (isset($_GET['sort'])) {
$sorts = array('date', 'ranking', 'page'); // ...
$_SESSION['orderby'] = (in_array($_GET['sort'], $sorts) ? $_GET['sort'] : 'STANDARD SORT');
}

use ajax send your var to php file to update session
$.ajax({
type: 'POST',
url: 'date.php',
data: {'date':date},
success: function(result) {
console.log(result)
}
});
date.php
<?php
session_start();
if(isset($_POST['date'])){
$_SESSION['date'] = $_POST['date'];
echo 'Date set to: '.$_SESSION['date'];
}
}

Related

Error to pass URL variable from index page to an autenticated page without change value

I did a searching in the similar questions, but I did not find a solution for my problem.
I would like to pass part of the URL from the index page to another function that is called if the user is autenticated. I can print the url variable in the next page, before the authentication. But since, the URL changes when the user is autenticated, I am getting a blank. How do I keep the value in the other page after the URL change?
In my index.php I call a js function that gey the course number when the page loads:
<body onload="myFunction()">
The myFunction is js code in data.js file that get part of the URL:
const url = location.href;
const urlCourse=url.split('=')[1];
document.getElementById("demo").innerHTML = urlCourse.toString(8);
}
In the callCourses.php, I have:
const course='<p id=demo></p>';
echo course; // It works!
if ($GLOBALS['authenticated'] ) { //here the URL will change because the user is now authenticated
echo course; // Error does not get the course number.
If the url is changed after authentication and if you have no access to changing that url, you will need to store that variable in one of the following places:
On the Server
Cookies
Session Cookies
// Before authentication
$_SESSION['courseNumber'] = getCourseNumberFromURL();
...
// In authenticated
$courseNumber = $_SESSION['courseNumber'];
Web Browser
Local Storage
Session Storage
// Before authentication
localStorage.set('courseNumber', getCourseNumberFromURL())
...
// After Authentication
const courseNumber = localStorage.get('courseNumber')
Edit - Expanded Answer
So, I think some clarification is needed here. PHP and JavaScript can't actually communicate with each other in the way I think you are understanding. You can use PHP to generate dynamic scripts, but once the html has been sent to the user, PHP can no longer interact with or manipulate that page. This means you can't access a JavaScript variable via PHP.
If we need to send JavaScript data over to our server, we perform one of two actions:
Create a custom form and send it to a PHP endpoint.
Make an XMLHttpRequest.
For 2, I recommend looking into fetch, which is highly supported in all modern browsers. (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)
With that explanation out of the way, here is what I recommend doing for your case:
<?php
// Whatever you had before
// Store the courseNumber if we haven't already
if (!$_SESSION['courseNumber']) {
$_SESSION['courseNumber'] = $_GET['courseNumber'];
}
// More junk
// Now, let's check if authenticated:
if ($GLOBALS['authenticated'] ) {
// We are! Let's echo the courseNumber
echo $_SESSION['courseNumber'];
// Or, if you need to do it in a tag, try this:
// This directly inserts the data as the page is being generated to send by PHP
echo "<p id='demo'>".$_SESSION['courseNumber']."</p>";
// Or do this if you have to have the JavaScript insert the value for some reason
echo "<p id='demo'></p>";
echo "<script>document.querySelector('#demo').innerText = '" . $_SESSION['courseNumber'] . "'</script>";
}
?>

How to pass a GET value when using history.back()?

I have a variable to check if the data is present already in the database.
If the data is already present it would go back to the form page to input a new data. Here is what I have
<script type="text/javascript">
window.history.back();
window.location = 'register.php?msg='<?php echo 1;?>
</script>
Also I have tried this but I don't know how to pass it in the URL:
<script type="text/javascript">
window.history.back();
window.alert('<?php $msg = 1; echo $msg;?>')
</script>
You can use History API to change the url:
history.back();
history.replaceState({}, "Registration", "register.php?msg=1");
location.reload();
You can use:
window.location = "baseurl/route?get=var"
instead of
window.history.back()
You need to be able to have baseurl as your global variable. Have it sent from your server and set in javascript as a global variable.
using browser back is fragile since you cannot predict (or check) where would that lead the user.
instead I would recommend that upon the relevant user action or business logic the app would explicitly navigate to register.php page with your desired parameter
// some code handling
var dataAlreadyPresent = checkIt();
if (dataAlreadyPresent) {
window.location = "/register.php?msg=yourMsg";
}
BTW, keep in mind that this URL is saved and users might bookmark it or forward it along, so may I suggest that the register.php server logic better not act automatically based on that input. you might want to clean the history state using replaceState (as per jcubic answer) once the register.php has loaded.

How to make changes to HTML document permanent using Javascript?

I have a simple like counter code, but the changes made disappear
after the page is refreshed.
Why does this happen, should this be done using PHP ?
How can this code be written much more efficiently, just for the knowledge anyway this is not the main question.
var like=document.getElementById("like__image");
addEventListener("click",function(){
var likeBox=document.getElementById("like__box");
var likeAdd=Number(likeBox.textContent)+1;
likeBox.textContent=likeAdd;
});
According to my understanding, you need this count to be global and to be available to all the users who access your page. Javascript is a client side script and the only file you can create using this is a cookie. In this case, you can't use cookies as it is created separately for each user.
For persistent result use a database or if you are not using a database for your application/website you can use a file (like .txt or .xml) to save your count and next time you can read from that file to display it again. But generally using database is recommended over a file system.
Using file system:
For main file we have a small php code to get the existing like count and an ajax function requesting like.php file when a user clicks on the like button.
HTML body:
<?php
$likeFile = 'like.txt';
/* check if the like file exists*/
if(file_exists($likeFile)) {
/* read the only the first file of the file as we don't intend to have more */
$file = fopen($likeFile, 'r');
$like = fgets($file);
fclose($file);
if($like) {
/* if we get the line split the string "likes=number" and get the existing count */
$likeCount = end(explode('=', $like));
}
} else {
$likeCount = 0;
}
?>
Like <span id="count"><?php echo $likeCount ?></span>
Javascript:
<script type="text/javascript">
function like(){
$.ajax({
type:"POST",
data: {like:true},
url: "like.php",
success: function(result){
$('#count').text(result);
}
});
}
</script>
In the like.php, we are checking for the post variable "like" just to be sure that we don't simply increment the like on direct access to this file. Here we are checking if the like.txt file exists or not. If true, it gets the first line like=1, get the count, increment the count and return it back to the ajax request. If false, it simply creates the file like.txt with like=1 for the first and only time.
<?php
if(isset($_POST['like']) && $_POST['like'] == true)
{
$likeFile = 'like.txt';
/* check if the like file exists*/
if(file_exists($likeFile)) {
/* read the only the first file of the file as we don't intend to have more */
$file = fopen($likeFile, 'r');
$like = fgets($file);
fclose($file);
if($like) {
/* if we get the line split the string "likes=number" and get the existing count */
$likeCount = end(explode('=', $like));
$likeCount++; /* increment the count by one */
file_put_contents($likeFile, 'likes=' . $likeCount); /* write the new count the same file and save it */
echo $likeCount; /* return the like count to the ajax request */
}
} else {
/* if file does not exist create it for the first time with count 1 */
file_put_contents($likeFile, 'likes=1');
echo '1';
}
} else {
return 'Something Wrong!';
}
Hope this is clear enough and helpful for you.
I suggest looking to cookies if you want to keep track of information across page reloads in a simple way. If you want the information to be available to anybody other than the user who created it, you'll likely need some form of server-side persistence such as a database.
The javascript is reloaded when the page is reloaded, so it's natural that the changes are lost as well.
You can, however, store them permanently, either in a web service, or preferrably in localStorage. Then you can retrieve from localStorage on page load.
Using PHP probably wouldn't help without storing it somewhere.
I don't think your code could be written that much more efficient.

Ajax after success, how to pass data to a variable to php

I have script like this
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
I don't know how I can pass data response to php code ?
For Example: if I alert response, it's show 123 .so I want pass value 123 to a variable in php
$id = 123
response is the result passed BY php, not TO php. What's passed to php is the id and the task.
In your tab.php, you can access these two values :
<?php
$id = $_POST['id'];
$task = $_POST['task'];
//do anything you want with it...
?>
This is not the right workflow. PHP executes on runtime, so every time the page has finished loading you can't really put variables back into PHP (unless you reload the page). This is where AJAX comes in, so you can call PHP scripts from JavaScript / jQuery and don't have to reload the page every time.
The right thing to do is to either store the variable you have generated in the tab.php script in a database, $_SESSION, $_COOKIE or something similar like so:
//put this at the top of all your php scripts you want to use the variable in
session_start();
//now store the variable you wanted to pass (in tab.php)
$_SESSION['returnValue'] = $myValue;
Now if you want to use the variable in other pages just echo it like so (remember to add session_start() at the top of the PHP script.
echo $_SESSION['returnValue'];
First of all, start by reading this
To answer your question,
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
The result from id and task are sent via $_POST (type:"POST") to the page tab.php (url:"./tab.php"). If you want to do that on a different page, just change the url in your ajax call: url:"./any_other_page.php" and the posted values will be sent there
Finally, read THIS post as well. It is greatly written and very well explained.
Hope it helps!
Keep on coding!
Ares.

Yii redirect from controller action after ajax call not working

I use the following buttons in my view file (don't pay attention to second one, but I just wanted to show you why I'm not using a normal form submit):
<?php echo CHtml::Button('Search Symptom(s)', array('id'=>'search')); ?>
<?php echo CHtml::Button('Add Another Symptom to Search', array('id'=>'addSymptom')); ?>
When the user clicks the buttons this javascript runs (it's inside a document.ready function)
$('#search').click(function()
{
//create new symptom in javascript
var newSymptom =
{
symptomCode: $('#symptomToBeSearchedCode').val(),
dateSymptomFirstSeen: $('#dateSymptomSeen').val(),
symptomTitle: $('#symptomToBeSearchedTitle').val()
};
//pass new symptom into symptomsList array
symptomsList.push(newSymptom);
//make ajax call to server
$.ajax({
type:'POST',
url: '/mysymptomsbook/index.php?r=symptomhistory/search',
data:{symptomsList: symptomsList} ,
dataType:'html'
});
});
symptomsList is an array with JS objects
This is the code in my controller action:
if(isset($_POST['symptomsList']))
{
foreach($_POST['symptomsList'] as $symptom)
{
//populate symptom search model attributes with user id, current date, and form input
$newSymptom = new Symptomhistory;
$newSymptom->setAttributes(array(
'user_id'=>Yii::app()->user->id,
'dateSearched'=>date('Y-m-d'),
'symptomCode'=>$symptom['symptomCode'],
'dateSymptomFirstSeen'=>$symptom['dateSymptomFirstSeen'],
'symptomTitle'=>$symptom['symptomTitle'],
));
//save search history
$newSymptom->save();
//add into the searched for symptoms code the latest code
array_push($symptomCodes, strval($symptom['symptomCode']));
}
$this->redirect(array('disease/index'));
}
I was planning on using redirect to send the $symptomCodes array to the other controlleraction (DiseasesController and actionIndex), but even without passing anything the redirect doesn't work. The models get saved to my database normally.
Anyone have any idea what is wrong? I'm thinking it has to do with Ajax since it's waiting for a response, but I want my controller to redirect instead. Any help as always, is greatly appreciated :)
I had similar problem, recommend you to look at this topic at official forum:
redirect not working when called via Ajax-Request
See the last answer in topic.

Categories

Resources