Passing javascript variables to php - javascript

I am now on a php page that has presented the user with some choices and I have saved the users input in 5 javascript variables:
product_format
product_print
product_paper_weight
product_paper_type
product_quantity
I want to send them to a a calculate.php page that will do the calculation of the price and then include calculate.php on my page and present the user with the price dynamically. I have read send javaScript variable to php variable
that I can use:
window.location.href = "calculate.php?name=" + javascriptVariable (and the rest);
And then I could use php get to calculate by querying the database. I also need this to be done continously as soon as the user changes an option I need to recalculate the price and present a new price.
Is this possible? Is there a better approach? Am I thinking right? Should I instead calculate the price by loading the php-sql data into javascript and calculate in javascript instead? Which is quicker and more secure?
The page http://www.reclam.se/trycksaker.php?product_id=1

This is a perfect application for AJAX. Much easier if you use jQuery, though you can do it in pure Javascript. Essentially, create a Javascript function that takes place when a field is changed (e.g., $('.product').change(function() { }); if you set class="product" on all the relevant input fields) and in that function use $.ajax to post the data to your PHP form.
You can do all the calculations in Javascript. If the data is dependent on database lookups or relatively complex math then AJAX makes more sense. If the calculations are very simple then you can embed the calculations directly in the .change function.
Using window.location.href= will cause a full page load, which does not sound like what you want.

As we all know this very well that php code runs on server side and javascript on client side. To transfer data between client and server, we need some kind of data transfer protocol and thats where Http comes in. You can send data to php server from client side either by Form or Ajax call with http get or post method.And once data are sent to php server, you can catch those data using php super globals $_GET or $_POST.

Related

Set SESSION on php and remove it via JAVASCIPT [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;
}
?>

How to send data to another page without using cookies or JS in PHP?

So, I have a PHP file that runs an SQL(MySql) query and gets the result. I need that page to send that result to another page automatically(I can use PHP in the receiving page). However, I want to make my website accessible to privacy-sensitive people who disable cookies and javascript on their browsers. I'm not using any PHP frameworks.
An initial page that runs the query only runs in the backend like a controller so it does not have any HTML in it. This means I cannot use a hidden form and make the user submit it with a button. I thought about sessions but they need cookies to work and JSON needs javascript. I thought about sending the data in the URL but the query result is quite big and I was afraid it could exceed some kind of URL length limits(if such thing exists). Is there a way to achieve this reliably?
EDIT: To clarify some things, the data I am sending is a search result so the query changes depending on the users input(which was provided to the page which runs the query with a form).
Store data somewhere and send id or something through query string and access data from database through that id from query string. Sending too much data is not advisable through cookies, session or even query string just pass your unique id and grab data from db.
Happy coding.

Passing large amounts of data from one page to another without POST?

I'm using a web server framework which works with only GET requests, at the moment I'm trying to pass a large amount of data, that is the text content in a textarea which comes from user input, into another page which echoes the user's input.
I've attempted Querystrings but I end up receiving the error "Requested URL too long".
Any suggestions as to what method I should use?
If you can only send data encoded in GET requests, then you will have to break up the request and send it in multiple parts.
You could either use Ajax or store the entire set of data in localStorage and fetch each chunk in turn as the page reloads.
One approach would be to make a request to an end point that allocates you a unique ID. Then send a series of requests in the form: ?id=XXX&page=1&data=... before closing it with ?id=XXX&total_pages=27 at which point you assemble the different pieces on the server.
This way lies madness. It would be much better to add POST support to your framework.
Try using Javascript Cookies.
you can store the textarea value there and then read it in another page (or wherever you want).
Here's a tutorial
http://www.w3schools.com/js/js_cookies.asp

How to do a MySQL query with AJAX without revealing db user password?

I'm new to JavaScript and AJAX. My experience is mostly in PHP. How can you do a MySQL query from JavaScript without revealing in the View HTML Source of the web browser the connection information for the MySQL database such as the db user's password? Thanks!
You make your JavaScript request the information from a PHP script, which checks the user's login cookie (like any other page would) and queries MySQL, returning the information to the JavaScript in whatever form it needs (JSON, usually).
In this case you don't perform the actual database query from the JavaScript code. The fact that it's using AJAX doesn't move database connectivity to the client, it just allows you to request information from the server without refreshing the page (as well as potentially moving some of the UI logic to the client).
Your AJAX call would simply make a request to a PHP file in your website which could:
Render part of a page, where the JavaScript code from the other page which called it would insert that markup into the open page. Or;
Render data, usually in JSON format, which the JavaScript code from the other page would read and use.
So let's say you have PageA.php which has a bunch of HTML and JavaScript. You want some of that JavaScript to make an AJAX call to the server to get data. You'd create a PageB.php which behaves just like any other PHP code, but instead of using HTML between the PHP code fragments (or in echo statements) it would use JSON syntax to represent the data being returned.
The JavaScript code on PageA.php would make an AJAX call to PageB.php, read the data that's returned, and use it in the HTML of PageA.php entirely client-side without having to refresh PageA.php.

Load mysql's value into javascript

i have stored values in mysql and i want to retrive that value in webpage
but the webpage is creted only using javascript
so how can i use that database's value in javascript
You need to have a server side script in the middle so you can retrieve the value using ajax.
What you're asking for is only possible with a restful nosql database like CouchDB.
You really need to give more information as to what you want to do, but as you implied that the page isn't dynamic the method would be to use ajax to request a dynamic page (written in a sever side langugage) that retrieves the data from the database and outputs it in the required format.
You'll need to either...
a) Have a separate, server-side script which can run the appropriate query, and then pass through the data to the page through an AJAX-type call (jQuery et cetera have functions to simplify the AJAX side of things, if you so desire),
OR
b) Put some server-side code into the page that is evaluated before the page is served and writes the data into the page within something that the Javascript can access it from (i.e. the definition of a variable or some such).

Categories