I have a php file. I click on and with onclick I call a javascript function with a parameter passed. This parameter is received on javascript function like a var, but into this function I want add this to $_SESSION php var.
script language="javascript">
<?php
session_start();
?>
function recargar(myVar){
var variable_post="Mi texto recargado";
<?php
$_SESSION['b'] = variable_post; //Here I want add myVar
?>
});
}
</script>
</head>
<body>
<div id="recargado">My text</div>
<p align="center">
recargar
</p>
</body>
</html>
I know that this could be a wrong way, how can I do this possible or in a similar way?
Thanks!!
You can only manipulate $_SESSION on the server, but JS code runs only on the client. The easiest way to do that would be with an ajax call, which will look like this, assuming you're using jQuery:
function recargar(myVar){
var variable_post="Mi texto recargado";
$.get("setsession.php?var="+variable_post);
});
}
This will run the setsession.php script on the server, without reloading the page. The setsession.php script will look like this:
<?php
$_SESSION['b'] = $_GET['var'];
?>
Of course, this code needs more work on error handling, but this is the general idea.
You won't be able to set php session through js but you can use cookies with javascript like this :
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
function checkCookie() {
var user = getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:", "");
if (user != "" && user != null) {
setCookie("username", user, 365);
}
}
}
Just call setCookie to set cookie, getCookie to get it and checkCookie to check it.
Javascript, loaded on the client-side like this, cannot write into a PHP variable directly, because PHP resides in the server-side.
To do what you want you will need to pass your Javascript variable to PHP in the server-side, via an HTTP request. It can be, for example:
clicking on a link like Click, which will reload the page (and there you will be able to do $_SESSION['b'] = $_GET['myVar'] ),
having a <form> submit, just like the link above,
or without re-loading the page by using AJAX, meaning "background" calls from Javascript to other pages without leaving your page. You can do AJAX calls in many ways, some of the other answers mention jQuery, a Javascript library that makes it easy to do such things. This post seems to explain it well.
use ajax, passing the variable to a php file.
Just below created a index.php file name in the header receives a script with an ajax, you will see that it is sending the variable you created to another file name file.php that receive so that you can process and return to the index.php file so you may make an append to your html.
I will put an example that the script's been a for variable returned can be treated the way you want.
If you do not know a lot of ajax follows the link via ajax jquery documentation.
http://api.jquery.com/jquery.ajax/
//---------------------------------------------------------------------------
index.php
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(
function(){
var variable_post="Mi texto recargado";
$.ajax({
url:'file.php',
type:'post',
data:{variable_post:variable_post},
success:function(data){
$('h1').html(data);
}
});
}
);
</script>
</head>
<body>
<h1>Text Here</h1>
</body>
</html>
//---------------------------------------------------------------------------
file.php
<?php
$_SESSION['b'] = $_POST['variable_post'];
echo $_SESSION['b'];
?>
//---------------------------------------------------------------------------
Remembering that using the browser features, for example in Chrome Inspect Element -> NetWork, you can check out everything that is sent back to the ajax a php page.
If you have any questions let me know.
Related
I would like to recreate several like button that saves count in a file.txt but that doesn't work :/
<?php
function getClickCount()
{
return (int)file_get_contents("counter.txt");
}
function incrementClickCount()
{
$counter = getClickCount() + 1;
file_put_contents("counter.txt", $counter);
}
?>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<script type="text/javascript">
var clicks = 0;
function onClick() {
clicks = 1;
document.getElementById("clicks").innerHTML = clicks;
};
</script>
<button type="button" onClick="onClick()" title="Vous aimez la couverture?" class="btn"><img id="heart" src="https://trello-attachments.s3.amazonaws.com/568304b85fa72dcb958a1edf/584acfc48b82595af77f2030/6257bf1efec79d5baf22309f8f327ce5/favorite.png" /></button>
<p><a id="clicks"><?php echo getClickCount(); ?></a></p>
DEMO HERE
Thanks in advance for your help, I am looking since days on the web to find it but I don't...
Alexander
counter.php
<?php
function getClickCount() {
return (int)file_get_contents("counter.txt");
}
function incrementClickCount() {
$counter = getClickCount() + 1;
file_put_contents("counter.txt", $counter);
}
if(!empty($_POST)) {
if($_POST['click'] == 'true') {
incrementClickCount();
echo getClickCount();
} else {
echo getClickCount();
}
}
?>
counter.txt
0
index.php
<html>
<head>
<title>Click Counter</title>
</head>
<body>
<button type="button" onClick="onClick()" title="Vous aimez la couverture?" class="btn"><img id="heart" src="https://trello-attachments.s3.amazonaws.com/568304b85fa72dcb958a1edf/584acfc48b82595af77f2030/6257bf1efec79d5baf22309f8f327ce5/favorite.png" /></button>
<p><a id="clicks"></a></p>
<script>
function onClick() {
loadClicks(true);
}
function loadClicks(isClicked) {
var click = isClicked === true ? true : false;
$.ajax({
url: 'counter.php',
type: 'POST',
data: {
'click': click
},
success: function(response) {
$('#clicks').text(response);
}
});
}
loadClicks(false);
</script>
</body>
</html>
Code Explanation
Whenever you click the button, there is an ajax request sent asynchronously in the background to counter.php. This PHP file receives request and process accordingly.
Here in the code, we send a single data to the PHP file in the ajax POST request which is a boolean data that is set based on the condition like if the button is clicked.
In PHP file, you will check a condition if the request is happened by button click or else other. If it is by button, you will increment the click and send the click counter value in response else you will only send the value.
You will notice I've called loadClicks function with the parameter true in onClick function and false outside the function meaning that I first call the loadClicks(false) as soon as the script is started its execution to load only the clicks value and later when I click the button loadClicks(true) is invoked meaning increment and fetch the value.
You will understand the code when you go through them carefully.
At first glance, I see 3 problems with your script.
1) You are mixing JavaScript and PHP. JavaScript runs on browsers and PHP runs on servers. If you want to exchange data between those parts of your script you need to make a server call from the JS part to the server, e.g. by using AJAX. A simple HTML request in JavaScript to a PHP script will work too.
2) Also your <button> tag needs to be embedded in a <form> should point to a script to be executed (can be the same script).
3) You never seem to call incrementClickCount(), at least not in the part shown here.
Suggestions
The would code everything in PHP and then address the other two points. Or you need to implement some form of client / server communication.
So basically, I got a php file where I create a script in the header.
In this script, I take the value of two textbox with document.getElementByID and I concatenate them in a variable. But now, in the same script, I want to send that var to a php section to use it.
I tried the ajax way, but since the php and the javascript is in the same file, it make an error.
Here is what the script section looks like :
IN FILE.PHP
<script type="text/javascript">
rowNum = 0;
function some_function()
{
var command = "somebasiccommand";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
<?php
$parameter = command; <----- obviously not working, but that's basically what im looking for
$output = exec("someExecutable.exe $parameter");
(...)
?>
}
</script>
EDIT 1
So here it is, I tried to use ajax this time, but this isn't working, seems like i miss something. Here is the server.php:
<?php
$parameter = $_POST['command'];
$output = exec("someexecutable.exe $parameter");
$output_array = preg_split("/[\n]+/", $output);
print_r($parameter);
?>
And here is my ajax call in my client.php (in a js script):
var command = "find";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
var ajax = new XMLHttpRequest;
ajax.open("POST", "server.php", true);
ajax.send(command);
var output_array = ajax.responseText;
alert(output_array);
For some reason, it doesn't go farther then the ajax.open step. On the debugger console of IE10, i got this error : SCRIPT438: Object doesn't support property or method 'open' .
You are trying to run a serverside script in your ClientSide script,
that's never going to work.
https://softwareengineering.stackexchange.com/questions/171203/what-are-the-differences-between-server-side-and-client-side-programming
If you want to do something with the data from text_1 and text_2, you should create a php file that can handle a post/get request via AJAX or a simple submit, featuring the data from those elements, and make it return or do whatever it is you want it to end up doing.
You can't use javascript variable (client) from php (server). To do that, you must call ajax.
<script type="text/javascript">
rowNum = 0;
function some_function()
{
var command = "somebasiccommand";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
//AJAX call to a php file on server
//below is example
var ajax = window.XMLHttpRequest;
ajax.open("POST", "yourhost.com/execute.php", true);
ajax.send(command);
}
</script>
And this is execute.php on server
<?php
$parameter = $_POST['command'];
$output = exec("someExecutable.exe $parameter");
(...)
?>
Alright... I pretty much changed and tested many things and I found out that the problem was the async property of the .send command. I was checking the value of the respondText too fast. Putting the third property of .open to false made the communication sync, so I receive the infos properly. I got another problem right now, but its not the same thing, so I will do another post.
this has been asked before, i want to do it so i can avoid refreshing the page caused by POST and GET, and ajax seems the right way
but i was wondering if i can make a cookie with javascript and then (from the same page) access it with php. is it possible?
small example:
//html code:
<form name="PLForm" onsubmit="myFunction()">
<input type="text" name="PLName"/>
</form>
//JS part:
myFunciton() {
var cname = "playlistName";
var cvalue = document.form["PLForm"]["PLName"];
document.cookie = cname + "=" + cvalue;
}
//in php:
<?php
$x = $_COOKIE["playlistName"];
//some code
?>
I have a web page that allows users to complete quizzes. These quizzes use JavaScript to populate original questions each time it is run.
Disclaimer: JS Noob alert.
After the questions are completed, the user is given a final score via this function:
function CheckFinished(){
var FB = '';
var AllDone = true;
for (var QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] < 0){
AllDone = false;
}
}
}
if (AllDone == true){
//Report final score and submit if necessary
NewScore();
CalculateOverallScore();
CalculateGrade();
FB = YourScoreIs + ' ' + RealScore + '%. (' + Grade + ')';
if (ShowCorrectFirstTime == true){
var CFT = 0;
for (QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] >= 1){
CFT++;
}
}
}
FB += '<br />' + CorrectFirstTime + ' ' + CFT + '/' + QsToShow;
}
All the Javascript here is pre-coded so I am trying my best to hack it. I am however struggling to work out how to pass the variable RealScore to a MySql database via PHP.
There are similar questions here on stackoverflow but none seem to help me.
By the looks of it AJAX seems to hold the answer, but how do I implement this into my JS code?
RealScore is only given a value after the quiz is complete, so my question is how do I go about posting this value to php, and beyond to update a field for a particular user in my database on completion of the quiz?
Thank you in advance for any help, and if you require any more info just let me know!
Storing data using AJAX (without JQuery)
What you are trying to do can pose a series of security vulnerabilities, it is important that you research ways to control and catch these if you care about your web application's security. These security flaws are outside the scope of this tutorial.
Requirements:
You will need your MySQL database table to have the fields "username" and "score"
What we are doing is writing two scripts, one in PHP and one in JavaScript (JS). The JS script will define a function that you can use to call the PHP script dynamically, and then react according to it's response.
The PHP script simply attempts to insert data into the database via $_POST.
To send the data to the database via AJAX, you need to call the Ajax() function, and the following is the usage of the funciton:
// JavaScript variable declarations
myUsername = "ReeceComo123";
myScriptLocation = "scripts/ajax.php";
myOutputLocation = getElementById("htmlObject");
// Call the function
Ajax(myOutputLocation, myScriptLocation, myUsername, RealScore);
So, without further ado...
JavaScript file:
/**
* outputLocation - any HTML object that can hold innerHTML (span, div, p)
* PHPScript - the URL of the PHP Ajax script
* username & score - the respective variables
*/
function Ajax(outputLocation, PHPScript, username, score) {
// Define AJAX Request
var ajaxReq = new XMLHttpRequest();
// Define how AJAX handles the response
ajaxReq.onreadystatechange=function(){
if (ajaxReq.readyState==4 && xml.status==200) {
// Send the response to the object outputLocation
document.getElementById(outputLocation).innerHTML = ajaxReq.responseText;
}
};
// Send Data to PHP script
ajaxReq.open("POST",PHPScript,true);
ajaxReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxReq.send("username="username);
ajaxReq.send("score="score);
}
PHP file (you will need to fill in the MYSQL login data):
<?php
// MYSQL login data
DEFINE(MYSQL_host, 'localhost');
DEFINE(MYSQL_db, 'myDatabase');
DEFINE(MYSQL_user, 'mySQLuser');
DEFINE(MYSQL_pass, 'password123');
// If data in ajax request exists
if(isset($_POST["username"]) && isset($_POST["score"])) {
// Set data
$myUsername = $_POST["username"];
$myScore = intval($_POST["score"]);
} else
// Or else kill the script
die('Invalid AJAX request.');
// Set up the MySQL connection
$con = mysqli_connect(MYSQL_host,MYSQL_user,MYSQL_pass,MYSQL_db);
// Kill the page if no connection could be made
if (!$con) die('Could not connect: ' . mysqli_error($con));
// Prepare the SQL Query
$sql_query="INSERT INTO ".TABLE_NAME." (username, score)";
$sql_query.="VALUES ($myUsername, $myScore);";
// Run the Query
if(mysqli_query($con,$sql))
echo "Score Saved!"; // Return 0 if true
else
echo "Error Saving Score!"; // Return 1 if false
mysqli_close($con);
?>
I use these function for ajax without JQuery its just a javascript function doesnt work in IE6 or below. call this function with the right parameters and it should work.
//div = the div id where feedback will be displayed via echo.
//url = the location of your php script
//score = your score.
function Ajax(div, URL, score){
var xml = new XMLHttpRequest(); //sets xmlrequest
xml.onreadystatechange=function(){
if (xml.readyState==4 && xml.status==200){
document.getElementById(div).innerHTML=xml.responseText;//sets div
}
};
xml.open("POST",URL,true); //sets php url
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("score="score); //sends data via post
}
//Your PHP-script needs this.
$score = $_POST["score"]; //obtains score from POST.
//save your score here
echo "score saved"; //this will be displayed in the div set for feedback.
so call the javascript function with the right inputs, a div id, the url to your php script and the score. Then it will send the data to the back end, and you can send back some feedback to the user via echo.
Call simple a Script with the parameter score.
"savescore.php?score=" + RealScore
in PHP Side you save it
$score = isset ($_GET['score']) ? (int)$_GET['score'] : 0;
$db->Query('INSERT INTO ... ' . $score . ' ...');
You could call the URL via Ajax or hidden Iframe.
Example for Ajax
var request = $.ajax({
url: "/savescore.php?score=" + RealScore,
type: "GET"
});
request.done(function(msg) {
alert("Save successfull");
});
request.fail(function(jqXHR, textStatus) {
alert("Error on Saving");
});
I'm trying to use jQuery to read all text files in a folder and display their contents, but then, filter which should ones should be displayed based on the name of the folder.
Here's the JavaScript:
var obj = {
"01600610/9874565214_789545621.txt": "",
"01600610/9874565214_789545622.txt": "",
"01600610/9874565214_789545623.txt": ""
};
$.each( obj, function(SavedText) {
$.get(SavedText, function(data){
$('#NewMessagesHolder').prepend('<div class="MessageClass">'+ '<span class="ChatName">' + CookieName + ' ('+ time + ')</span>' + ': '+ data +'</div>')
}, 'text');
});
On this:
var obj = {
"01600610/9874565214_789545621.txt": "",
"01600610/9874565214_789545622.txt":"",
"01600610/9874565214_789545623.txt":""
};
Q1: How do I get all text files inside a folder instead of specifying the file I want?
Q2: How can I filter? For example, how can I only get files ending or starting with 789545.
When these files are on your local filesystem, you can use the HTML5 Filesystem API.
If the files are located on a server, there is no way listing them from plain (client-side) javascript (maybe except a brute-force method, which shouldn't be considered of course). Then you have to write a server script (in PHP/Node/Perl/Phython/...) which will respond to a ajax request with a file list.
If you are using a server script, you should do the filtering on the server (so the answer depends on the language).
Otherwise you should use Regular Expressions:
var search = new RegExp("789545");
for(var file in obj) {
if(search.test(file))
alert(file+": "+obj[file]);
}
This would search for files with a name containing the pattern 789545
Please create index.php file and add this content to it. Create there a folder called "files" and add your files there
<?php
function contains($haystack, $needle){
if (strpos($haystack,$needle) !== false) {
return true;
}
return false;
}
if(isset($_POST['get_files'])){
$folder = "";
$filter = "";
if(isset($_POST['folder'])){
$folder = $_POST['folder'];
}
if(isset($_POST['filter'])){
$filter = $_POST['filter'];
}
$files = array();
foreach(glob($folder.'/*.*') as $filename){
if($filter != ""){
if(contains($filename, $filter)){
$files[] = $filename;
}
}else{
$files[] = $filename;
}
}
print_r($files);
exit;
}
?>
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function getData(){
jQuery.post('index.php',{
get_files:true,
folder:"files",
filter:""
},function(data){
jQuery('#container').html(data);
});
}
</script>
</head>
<body>
<input type="button" value="Get data" onclick="getData();" />
<div id="container"></div>
</body>
</html>
You can specify different folder, and filename filter in jQuery post request call
U can use regular expressions to filter the filenames. And for getting all files in a folder, U want to run a server side script. I use perl or php, to do this kinda stuff. U can use ajax to post the request and make the server script to return the file contents.
http://perlmeme.org/faqs/file_io/directory_listing.html
This link is just an example to do what u need in perl. And u could possibly do the same with other languages too