Save variable to text file serverside using jquery - javascript

I am trying to save a variable for counting the views of my personal website, I dont need to use php because its literally a viewcount. I know how to retrieve the count from the server using $.post, but how would I retrieve it (Edit: In the simplest way possible.)?
The website I'm trying to do it with is http://artsicleprojects.com/
Thanks in advance!

You will need PHP for this question, because it is dealing with server-side actions. First, you need to make a server-side script to increment the text file's number. Then, you will need to make a client-side script to make a request to the server. This script increments a number in the text file every time the request is made. Anyway, here's how I would do it (Note: this code is un-tested):
PHP:
<?php
/*Reads and collects current count.*/
$rfile = fopen("views.txt", "r") or die("Unable to open file!");
$count = fread($rfile,filesize("views.txt"));
fclose($rfile);
/*Increments the count.*/
$wfile = fopen("views.txt", "w");
$ncount = $count + 1;
fwrite($wfile, $ncount);
fclose($wfile);
?>
Note on code: for this code to work correctly, you may need a text file already made (views.txt), in the same directory as the PHP script, with a single "0" written in it.
JavaScript (with jQuery):
$.post("phpscript.php", function(data, status){
console.log(status);
});
This also is supposed to be in the same directory as the script to work.

Related

Add Variable to PHP Session Array From Dynamically created HTML element within PHP Echo [duplicate]

Is it possible to set PHP session variables using Javascript?
In JavaScript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
<div id='div_session_write'> </div>
The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.
If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.
or by pure js, see also on StackOverflow :
JavaScript post request like a form submit
BUT WHY try to set $_session with js? any JS variable can be modified by a player with
some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.
This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I
initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo'].
Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.
And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.
If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.
Then, after a js thinks we have a win, add or mod a button to change pages:
document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
var line='crimegameonline-p9b.php';
top.location.href=line;
}
Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the
$_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).
You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also
Javascript and session variables
jQuery click event to change php session variable
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION variable (say $_SESSION['v']=0) if SESSION is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');
Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.
be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.
here's an example of code that you wouldn't want to do..
<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>
Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!
If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.
I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.
The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.
$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
$.ajax ({
data: {"numElems": len},
url: '../../Utiles/GuardarNumElems.php',
type: 'post'
});
});
And the GuardarNumElems.php is as following:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>

PHP file called by javascript and another php file

I have a php file (I will call ORIGINAL) which do some calculations (through db mysql). I want to read this php from javascript. For that operation I have used ajax function and my php uses echo $result to print the data I need.
Everything is perfect here.
What happends now, I am creating another php file which need to call the ORIGINAL php file. If I want to call it, I must change the echo to return which is normal. This causes that my javascript call doesnt work.
Do you have a solution which work for both situations?
Thanks in advance.
Do you mean something like this?
original_php_file.php:
<?php
require_once "other_php_file.php"; // include all of the other files contents
// all code contained within original_php_file
?>
You were being pretty broad with your request (not including file names or code), so this is all I can assume you need.
Tell me if it helps :-)
Just send one more parameter into your ajax request to tell that ORIGINAL php file what type of output it should return.
Into your ORIGINAL file check for that output so you can understand from where that request come and what output you should return.
$.ajax({
url: 'ORIGINAL.php',
data: 'data=test&output=1',
success: function(r){
// here you have your output
}
});

PHPExcel pop up progress bar or waiting icon while generating excel file

I using PHPExcel to generate excel file, but due to some excel file is quite big, it takes time to generate.
When excel file is generating, I wish to add a popup that shows either progress bar or a waiting icon.
I've tried all the solution I found on google but still cannot be done.
I appreciate all kind of help.
$objPHPExcel = new PHPExcel();<br>
$F=$objPHPExcel->getActiveSheet();
//other's code to generate excel file
header('Content-Type: application/vnd.ms-excel');<br>
header('Content-Disposition: attachment;filename="report.xls"');<br>
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');<br>
$objWriter->save('php://output');<br>
exit();
The excel start to generate in this line of code:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
There is no way to have this work the way you are proposing. First, the headers you are creating will not allow html to show to the user. Also, the php hasn't finished processing so there is no way to go back to the user until the script is done.
Another option would be to call to the PHP script from Javascript asynchronously. Then return the file's name to the javascript, and redirect the user to the Excel file. Then you can show whatever you need to the user on the web page. Below is a very very very simplified example. But it could get you started.
php:
$objPHPExcel = new PHPExcel();
$F=$objPHPExcel->getActiveSheet();
//Other code to Generate Excel File
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('path/to/excelfile.xls');
//Now return some info to user
//You will want to actually do some testing here
//to make sure the file was created
echo json_encode(array(
"result" => 200,
"path" => "path/to/excelfile.xls"
));
jquery:
//Call to the php file above to start the processing
//You can add some spinner or popup message here
$.get( "path/to/phpexcel.php", function( data ) {
//Now check the return data
if(data.result === 200){
//If all is well just redirect the user to the file
window.location = data.path;
}else{
alert("Something went wrong!!!");
}
});
Again, this is very rough, but I just wanted you to have an option to pursue further.
Since this is an old post, I'll keep it short.
If you place a iFrame on your page and load your PHPExcel script into it with echoes placed at certain points of informing what is happening, you can simulate this. Other option is to load the PHP_Excel script as its' own page with the above echoes in place and a continue or return button that shows when the script is finished.

making a loop with jquery, Ajax and PHP

i want to make a loop in jquery, Ajax and PHP.
my pages are:
shop.php
do_ajax.php
in the shop.php are variable $p_productid is 1 and $j_productid is $p_productid
var j_productid = <?= $p_productid ?>;
now i do j_productid++ so the output from $j_productid is 2
now i'm posting this with ajax to do_ajax.php
in the do_ajax.php are variable $pa_productid is $_POST['$j_productid'];
now i can place this on html, but i want to set this value in too the variable on $p_productid on shop.php
how i need to do this?
there is working a swipe system in this case so only with php it isnt working i need to work with jquery that's why am i doing this on this way. i got an another solution without AJAX but i want that you cant see on the client side the webpage is refreshing.
JQUERY
wipeLeft: function() {
var j_ProductId = <?= $g_ProductId ?>;
var j_Swiped = 1;
if (j_ProductId < <?= $l_LastProduct ?>){
j_ProductId++
//document.swiping.productid.value = j_ProductId;
//document.swiping.submit();
$.ajax({
url: 'do_ajax.php',
type: 'POST',
data: { swipe : j_Swiped,
productid : j_ProductId},
success: function (data) {
$('.product').html(data);
}
});
}
}
do_ajax.php
if(!empty($_POST['swipe'])){
$l_ProductId = $_POST['productid'];
echo $l_ProductId;
}
You need to understand that the JavaScript (even if generated dynamically by PHP) is not running the same time that PHP is running. Your workflow will be something like this:
PHP script (shop.php) is invoked
PHP script generates output, HTML and JS mixed.
These are all in server side until the web server sends the output to client (browser)
In browser HTML displays and JS runs with starting values that you generated previously by PHP. But in this time, PHP has been finished, not running anymore. PHP variables are not alive anymore.
JS interacts with the user in browser, we can say it's running continuously.
Triggered by an action (swipe) JS sends an (ajax) request from client side to server side. This request transfers the new value to server side, and invokes another PHP script (do_ajax.php). You do whatever you want with the new value (process it and or store it) in server side. You need to understand that you are in a completely disjunct scope in PHP than in your first PHP script. (distinct in time too)
If you want to be sure that, in case of a page reload, the (product ID) value will be the updated value, you need to store it somewhere (user session, key-value store, database, or any persistent) when you get it in server side (so in do_ajax.php) and later load this value in the beginning of your shop.php script ...which will pass it to the JS, and so on. The workflow starts again.

How to update JavaScript variable using PHP

I have a JavaScript file named a pricing.js which contains this content in it:
var price_arr = new Array('$ 16.95','$ 30.95','$ 49.95','$ 70.95','$ 99.95','$ 109.95','$ 139.95','$ 155.95','$ 199.95','$ 460.95');
But I want to to update this part of JavaScript file using PHP so please help me in this how can I update this part of the content from JavaScript file using PHP?
'$ 16.95','$ 30.95','$ 49.95','$ 70.95','$ 99.95','$ 109.95','$ 139.95','$ 155.95','$ 199.95','$ 460.95'
Please understand that Javascript is Client Side code and PHP is server side code.
There can be 2 possible ways or scenarios which you want to achieve:
If you want to manipulate the JS file before sending it to client, you can rename the Javascript file to have .php extension and write php code to provide a variable. For Ex:
<?php
// write php code to create a string of values using a for loop
$price_array_string = "'$ 16.95','$ 30.95','$ 49.95',
'$ 70.95','$ 99.95','$ 109.95','$ 139.95','$ 155.95','$ 199.95','$ 460.95'";
// Javscript Code var price_arr = new Array(`<?`php echo $price_array_string ?>);
The other alternative is that you get the value of price array by making an Ajax Request to a PHP web service.
Simply give the pricing.js file a .php extension. You can then include PHP in the javascript file the way you would for any other page. Just be sure your HTML code specifies that it's still "text/javascript" when you load it. You'll probably want to set the content-type in the PHP file as well, like so: header("Content-type: text/javascript");
Using your PHP script you can put a value in an HTML5 data attribute of an element on your page and then read it from your JavaScript, e.g. <body data-array="'$ 16.95','$ 30.95'"> can be generated with PHP, and then read with JS: var are = new Array($('body').attr('data-array').split(',')). Here jQuery is used in order to read the attribute value, but you can also do it with pure JavaScript.

Categories

Resources