I want to set a session variable on click of a Button. But without clicking that button the session variable is set.
What is wrong in my code? Please help..!!
My script is -
<script>
$(document).ready(function(){
$("#next").click(function(){
<? $_SESSION["s_id"]=mt_rand(); ?>
location.reload();
});
});
</script>
PHP gets executed before you see the site. If this js gets rendered, php is already done with its work and wont do any more. If you want to set a session with a click on a div, you have to create a form and use $_POST to send the request back to the server.
Remember: You can NEVER execute php code like this in javascript. javascript is clientside, while php is serverside.
Session variables need to be set before a document outputs any data. You could possibly use an AJAX call to allow the session to be set in an external file on button press.
Related
I trying to do simple registration form with error message for wrong data format. Till now I have index page with form, submit button that send the data to .js file where I make the validation. The problem is that I can execute function in the index page from the .js file and update my span message, but my page reload and I lose it. How I can make message that survive the reload or better to return the message after page reload?
If a button is tagged as submit, the page always reloads, this is how the submit property works. Unless you redirect it specifically somewhere, it would reload. My suggestion is link it to a database. Store the contents of text inputs, etc in a variable or a document in databases such as firebase so that even after the reload the data is stored in the cloud or on a database somewhere.
Since its a form, you're anyways going to have to store the data on a database so try out firebase / AWS and see if it works for you. When it submits, have an onEvent (HTML) or a variable and 2 if statements (Have an if statement to change a variable from false to true / other way round when submit is clicked and another if statement for the value of the variable to store the data), or any other method that works for you as this will make sure the data is stored so it can be saved after a submission.
I decided to use input onfocusout="myfunction(name.value) so when you click outside of the textbox where you typing you will get text that show you where you must to make changes if something is wrong. The problem with this is that now I must to have my code inside .js and in same time in my index page. It looks to me very fishy, but I saw this type of forms in many sites, but I am not sure how they achieved it with no using their validation code this way.
I am very new to php and javascript and I was wondering how I could make a global counter that adds 1 to it every time a user presses a button. The number would stay the same even if someone is on a different computer or refreshes the page. I had this using javascript:
<script type="text/javascript">
var clicks = 0
function onClick() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onClick="onClick()">Click me</button>
<footer>Clicks: <a id="clicks">0</a></footer>
But when ever someone refreshes the page, it resets the number, and it is not global. I tried making something in php which is:
<?php
$clicks = 0
public function clickButton()
{
$clicks = $clicks + 1
}
?>
but I have no idea what I'm doing and how to call the php function or display the php variable.
Your current problem is that your Click variable is only storred on the one computer clicking.
You need to do 2 things:
Store the click variable.
Read the click variable.
(Live updates.)
Store the click variable:
As Vinicius Maia said you need a connection between the users and this can be done with a database, read about MySQL.
Or you can use a more simple method and use php to read and create / write the Click variable into a file named Clicks.txt. See PHP Filesystem Functions on W3C
Read the click variable:
If you chose the MySQL method you should use the commands as so, else if you chose the primitive method you can use the following command: Php File Get Content
Live updates:
To show the variable live and not making your users refresh you should be able to use AJAX so make sure to take a look at that. This question might be usefull.
You should make a interval loop which should constantly check for updates in the variable. This question might be usefull
Together:
Take a good look at Jonas w's answer, he gives a good example on how you could make this and he follows your request. Only downside by using this tactic is that everytime you click you refresh, which might be annoying for some users.
But what he does is:
He reads the variable.
When you click the button he runs the PHP code by opening it.
When done with the code he send you back to index and refresh the side
Repeat...
But for your users, maybe you should add the live function by using this system:
Read the variable.
Make a loop with AJAX that calls a php function that checks and return updates
When you click the button use AJAX to run another php function to update the variable
Repeat...
You have the right JavaScript logic, now you just need to store your clicks somewhere that won't be affected by a browser refresh!
My first suggestion would be to utilize HTML5's localStorage object.
The examples are pretty good on the link. See if you can make something work!
Javascript or PHP will not solve your problem. Just because what you need is some connection between all users that will access your website. For that, you must use some kind of database. I recommend you starting learning MySQL.
Check this: http://php.net/manual/en/book.mysqli.php
The php variables just work inside of one request. So if two people request your site, the script runs twice in two different versions. You have to store the variable on the server.
You could store it into a mysql database ( good articles about that on php.net)
or you could make a counter.txt and edit it with php. ("Fopen" on php.net)
The php runs on the server and cannot interact with the clients side js. You need to send this "button click" to the server. You can do this with AJAX ( google that) or reloading the site and passing gets and posts to the server
Update.php:
<?php
$file=fopen("counter.txt","c+");//open or create counter.txt
$counter=fread($file, 10);//read content
$counter=(int)$counter+1;//add one
fwrite($file,$counter);//save counter
fclose($file);//close file
Header("Location: index.php");//go back to index.php
?>
Index.php:
<?php
$file=fopen("counter.txt","c+");
$counter=fread($file, 10);
fclose($file);
Echo $counter;
?>
Click me
if you need that different users see the same counter, then you will need save the counter in a database.
Regards.
So.
In a LAMP stack (PHP), I've got this situation where I'm showing an intermediate page based on some variable from the first page --more simply, I have one page called, say, ListOfProjects, from which I can select a project to view.
When I go to that project, there are other page-navigation elements (like looking at individual jobs in the project, say) the user can click. Once I click them, and am navigated away from the intermediate page between ListOfProjects and IndividualJob, I have to resubmit the data that got me there.
That's fine, and if I could do it automatically, I would. However, I haven't found a way to force this behavior and eliminate the extra click and the ugly "Confirm Form Resubmission" screen.
Does anyone know a way I could A) silently force form-resubmission when the user hits the back button or B) avoid the situation where there's a form that needs resubmitting?
I've thought about trying to just pass that project ID to the session variable, but it's well within scope to have more than one individual project open in the same browser, which would make that unwieldy.
Thoughts? Suggestions?
Thanks!
Don't use POST.
When you are getting data from the server, use GET and put the data in the query string.
POST is designed for sending data to the server that will make a change (e.g. updating data in the database), it isn't appropriate for just deciding what data to look at.
Some solution is bypass using jQuery to resubmit a form when click on back:
<?php if (isset($_POST['ListOfProject'])): ?>
<form method="POST" id="backToProject"></form>
<script>$("#backToProject").submit()</script>
<?php endif ?>
Another solution is to use header("Location: ...") to force users to redirect a page, BUT you should remove all previous $_POST request using unset($_POST) such as:
unset($_POST);
header("Location: your_uri://your_path");
Try reload a page and reload a page using javascript into <script> tag such as:
if ($_POST['ListOfProject'])
{
echo '<script type="text/javascript">location.reload();</script>';
}
Try to understand GET/POST method: https://en.wikipedia.org/wiki/Post/Redirect/Get
And I don't recommended using link of sites using $_POST method such as say Quentin user.
So, I am creating this website that sets the sessionstorage variable 'logedIn' to true when the user succesfully logs in like this:
sessionStorage.setItem('logedIn', 'true')
That variable is used on the other webpages to see if the user is logged in before showing content, so that users who aren't logged in can't have access to the webpage. It works like a charm, but I have noticed, that if I manually type the code in the google chrome console, I can easily change the sessionvariable. This is obviously not wanted.
My question is: how can I resolve this problem?
PS: the reason why I don't use PHP session variables is because the login procedure is done with javascript. When the login button is pressed, ajax sends the given credentials to a php script, which checks the database. If it is successfull, it sends back a code to the ajax complete function, which sets the variable. If you have a better method of doing what I need to do, you are very welcome ;)
Thanks, Zeno
You can't and it's not safe. After AJAX result you should set cookies and validate them on every page on the server side.
I have a strange problem. I have set a query to insert two names in the database. I have also used Javascript(Jquery) to run it only when the create button is clicked. But it runs evry time I reload the page...
Button:
<button id="button-create" type="button" style="float:right;">Create</button>
Script:
$(document).ready(function(){
$("#button-create").click(function(){
$('body').append('<div class="box" id="12"><div class="head">Homework<button class="button-delete" data-panelid="12" type="button" style="float:right;">Delete</button></div><div class="text">Valkommen!</div></div>').children(':last').hide().slideDown(500);
<?php
$query123 = $pdo->prepare("INSERT INTO post (head, content) VALUES ('John', 'Doe')");
$query123->execute();
?>
});
});
It is because your PHP script is executed every time your Server, for example Apache, serves that page or in trivial terms, the user reloads the page.
The reason that it does that is because it's PHP-code. When rendering the PHP-file, the server will execute ALL of the PHP. So when you run the page, it will run that php code before it goes to the browser...
All the PHP will be executed and only the output from the PHP will be sent to the browser. So your database execute will be executed already.
PHP code => Running on server
JS code => Running in browser
There is no way they can communicate directly.
If you want to do something like this, you need an ajax call to a page that will execute the SQL Query.
I would recommend to watch this introduction to the difference between PHP and Javascript: https://www.youtube.com/watch?v=dJJvK3Fre0I