Creating dynamic order basket using php javascript - javascript

I am creating an ePos system, that adds any item user clicks to the basket and calculate the total in the end all done without total page refresh.
I tried using $_SESSION and storing as order ( [item] => [price] ) but failed, as i need to refresh.
what I need is:
to display added Items [id name Qnty price]
calculate total price of added items.
please advice me on the best method to do this.
thanks
this is what I attempter in javascript
function addItem(name, price, id)
{
var table=document.getElementById("basket");
var row=table.insertRow(-1);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var cell3=row.insertCell(2);
cell1.innerHTML=name;
cell2.innerHTML=1;
cell3.innerHTML=price;
}
but my issue was, i could not find a way to add decimals, parseFloat made alot of bugs for me

You should not need to refresh the page in order to save information into the PHP Session object. PHP Session information is stored on the server, so you can do an asynchronous HTTP request to the backend, and store information the PHP Session. I would suggest using the jQuery.ajax function (http://api.jquery.com/jQuery.ajax/) to do your async HTTP requests. If you are not familiar with jQuery, I highly suggest you get familiar with it. I also suggest you look into how AJAX works.
Also, if you are using the PHP session, if you are not using some kind of framework which does session management, you must make sure to call session_start() before using the $_SESSION variable.

Related

Show same content at same time in different browser

I am developing a numbers game where users will buy numbers and after 2 days winners will be drawn.
I am using PHP for the backend and jQuery for the frontend.
My problem is when drawing occurred user on different browser can't see same numbers, these draw numbers are being generated by PHP.
I was thinking maybe I can build these game by PHP and Javascript but it looks not easy. Can you guys please suggest some alternative? How can I improve this code to show the same number on the different browser?
I have the idea that it is not possible to generate a random number for each request. Maybe I can save the number in the database and then get this number in PHP such that the number will be unique for each request.
The actual issue is to create the same content for each user in different browsers. Any help would be really appreciated.
Javascript:
var myTimer = setInterval(checkDrawDate, 1000);
function checkDrawDate() {
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time;
var x = new Date(dateTime);
var y = new Date("{{$drawDate}}"); //this is laravel variable which contain drawdate e.g. 2017-07-05
if(x >= y){
drawNumber();
}
}
function drawNumber(){
$.get("{{ route('ajaxcomparepowerball') }}",{'gameId': gameid}, function(res){
$('#mybets').html(res.html);
});
}
PHP:
public function ajaxDrawNumber(Request $req){
return rand(0,49);
}
A Cron Job will be needed to implement this functionality. As you are drawing a number on particular time (after $drawDate in your case). So the cron job will execute once in day, check whether $drawDate for each game is today or passed. If condition true, $drawDate <= now, call a function to generate random draw number rand(0,49) and save it to database corresponding to gameid of matched games(having $drawDate <= now).
By doing this, a lot Javascript work will be reduced. In JS, then need to hit an ajax request with gameid to fetch record having draw number for particular game from database. If record not found, it means random number not drawn yet.
I think you are using Laravel, so to schedule tasks in laravel visit here.
Here some possible solutions.
If you need the same data modified for users in real time I think the best option is WebRTC, quick start here. And here a simple example sending strings in real time between clients.
If you also need interaction server to client you could use server-sent events.
You could perform a bidirectional communication between browser and a server using WebSockets. You can send and receive event-driven responses. Using a database you could communicate two clients.
The easiest is using a database to store the information and perform ajax to send data to the server (and database) and server-sent events to send data to the clients.
Basic Server-sent event example:
Javacript:
var evtSource = new EventSource("myserver.php");
evtSource.onmessage = function(e) {
// listening for new messages here
alert(e.data)// e.data is mynumber
}
Php (myserver.php)
<?php
header('Cache-Control: no-cache');
header("Content-Type: text/event-stream\n\n");
while (1) {
//perform a query in your database with your driver
$result = mysql_query("SELECT mynumber FROM mytable WHERE user = 1");
$row = mysql_fetch_assoc($result);
echo $row['mynumber'];//<-- sending mynumber to client
ob_end_flush();
flush();
sleep(1);// <-- this is every second, but you could fire this with ajax or some other event.
}
This code send a number from server to a client that is listening. If a user made a change, one possibility is that client send an ajax to update some value in the database. So, at the same time, the ajax server could send this as an update to clients listening. In that way the whole process is completed.
I think all you need is this. Call a function in every, say 5 seconds or less and fetch data from server and update it in the page.
window.setInterval(function(){
updateNumber();
}, 5000);// set for every five seconds
function updateNumber(){
//ajax code to fetch live data and append the data in the numbers container
}
And dont forget to cross check the data before saving the numbers in the server.
Hope it helps.!!!
To save and maintain users state, key value store like Aerospike can be used. It is very easy to save and retrieve data in key value store. In above case we just have to generate a unique key using gameId, userId and date. And save user's data against the unique key.
To get started with Aerospike php client following is Aerospike php client
If data is present against the unique id for that particular user just return it, else create the new random number save it against the unique key and return it. Please be careful while creating unique key. Instead of using server side date-time please send date in ajax call request so there will not be any issue with time zone. It will be always user's timezone and there will not be any issue if server is in different timezone and user is in different timezone.
function drawNumber(){
$.get("{{ route('ajaxcomparepowerball') }}",{'gameId': gameid,'date':user-timezone-date}, function(res){
$('#mybets').html(res.html);
});
}
Here "user-timezone-date" should be fix date format like 'MM-dd-yy' which will indicate the same day. hours or seconds should not be included while generating unique key otherwise at the time of retrieving the user's state; generating particular unique will be changed every hour or every second and whole purpose of of doing this will be shattered.
I am new to StackOverFlow so I am not able to comment on the answers. In case of corn job as well we have to be careful with time-zones if server and users are in different time zones. Otherwise user's will see different random number before user's day is complete. Please improve answer by commenting on it and suggestions are always welcome.

Change URL data on page load

Hello I have a small website where data is passed between pages over URL.
My question is can someone break into it and make it pass the same data always?
For example let say, when you click button one, page below is loaded.
example.com?clicked=5
Then at that page I take value 5 and get some more data from user through a form. Then pass all the data to a third page. In this page data is entered to a database. While I observe collected data I saw some unusual combinations of records. How can I verify this?
yes. as javascript is open on the website, everyone can hack it.
you will need to write some code on you backend to validade it.
always think that you user/costumer will try to hack you sytem.
so take precautions like, check if user is the user of the session, if he is logged, if he can do what he is trying to do. check if the record that he is trying get exists.
if u are using a stand alone site, that u made the entire code from the ashes, you will need to implement this things by yourself.
like using the standard php session, making the data validation etc.
or you can find some classes that other people have made, you can find a lot o this on google. as it is a common problem of web programing.
if u are using a backed framework that isnt from another world, probably already has one. sp, go check its documentation.
html:
<a id = 'button-one' name = '5'> Button One </a>
javascript:
window.onload = function() {
document.getElementById('button-one').onclick = function() {
changeURL(this.attributes.name.value);
};
};
function changeURL(data) {
location.hash = data;
}

Not able to copy data from one table to another

I have two tables: trade and user_pokemon_db
I want to copy a specific rows from user_pokemon_db, when an event occurs.
Html code:
echo "<a href='tradecenter.php' onClick='document.write(".trade($db_id).")' >Put in Trade</a>";
When the user clicks on the link, the php function is called which consists on sql query to copy the row.
$sql = " INSERT INTO trade (trade_id, user_id, pkmn_id, level, exp, health, attack1, attack2, attack3)
SELECT (id, user_id, pkmn_id, level, exp, health, attack1, attack2, attack3)
FROM user_pokemon_db WHERE user_id = '".$id."' AND id = '".$db_id."' ";
Problem maybe due to improper writting of the query.. or maybe due to improper formatting of the href!??
What should I do?
I don't know the content of your php function trade() but it seems that you are confusing javascript and PHP.
Keep in mind that in most of case, once the web page is sent to the user browser, the PHP execution is finished. If you want to do a SQL request after a link click, you need to load a new page or to use something like Ajax to run some PHP code again.
The simplest way to do what you want is to pass the pokemon id as a GET variable (= in the URL)
and check this variable on another page and generate the good SQL query :
echo '<a href="trade.php?pokemon_id='.$id.'" >Trade </a>' ;
And the trade.php would do something like that :
$id = $_GET['pokemon_id'] ; // Be Aware of SQL Injections !!
trade($id);
Have a look at this page for more information about forms : http://www.w3schools.com/php/php_forms.asp
( And if you are using GET or POST variables in your SQL query, be aware of SQL Injections )
If you want to run your PHP function without reloading the page, you should use AJAX. Check this page to understand how it works. A very easy way to use it is to use jQuery

Jquery / Javascript - get list of request URLs for that session like in browser console

I need to be able to retrieve the list of request URLs that are displayed in the browser console, i.e: GET http://mydomain.com/index.php?p=1&curr=GBP&cat=Food. 200. Users can click around my app and apply different filters and scrolls through pages and I need some way of tracking this so that I always know what data has already been loaded for that users session.
I had thought about using PHPs $_SERVER['REQUEST_URI'] and saving them in a session but then I don't know how I would access this session from my JQuery as its JQuery that constructs the URLs.
Has anyone any idea how I can access this data from the console? Is this possible? If not can anyone suggest a workaround?
The PHP / JQuery mess I have so far:
<?php
session_start();
//keep track of requests.
if (!isset($_SESSION['requests'])) {
$_SESSION['requests'] = array();
} else {
if (!in_array( $_SERVER['REQUEST_URI'], $_SESSION['requests'])) {
$_SESSION['requests'][] = $_SERVER['REQUEST_URI'];
}
}
$requests = json_encode($_SESSION['requests']);
print_r($_SESSION['requests']);
print_r($requests); //these both have values
?>
//further down the page is the javascript
$('.filter a').click(function(e) {
var $this = $(this);
var $optionSet = $this.parents('.option-set');
var group = $optionSet.attr('data-filter-group');
filters[ group ] = $this.attr('data-filter-value');
//***more code for filtering etc******/
var paginate_url = $('.paginate a').attr('href');
//THIS IS PART I CANNOT GET WORKING
var visited_urls= <?=$requests?>;
//console.log($.parseJSON(visited_urls));
console.log(visited_urls); //is always empty
var pageno = ''; //somehow check to see if the URL that has been clicked exists int he requests array, if so get the page number and increment.
var next_url = UpdateQueryString(paginate_url, pageno, group, encodeURIComponent(filter_qry));
I'm not completely sure what you're trying to do but I think you can skip the PHP and just use JavaScript and sessionStorage: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage or localStorage: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#localStorage (depending on how persistent you want the data to be)
For example if I want to listen for all clicks on 'a' tags and track whether those hrefs have been visited (and how many times)
$(document).ready(function() {
// store an empty object in session storage when the page loads
sessionStorage.visited = JSON.stringify({});
});
$('a').on('click', function() {
var storage = JSON.parse(sessionStorage.visited),
href = $(this).attr('href');
// when we get a click check to see if this has been clicked before
if (!storage[href]) {
// if not save it and set the count to 1
storage[href] = 1;
} else {
// otherwise increment the count
storage[href]++;
}
sessionStorage.visited = JSON.stringify(storage);
});
If you want to save the urls from your ajax calls the same principle applies but listen for the ajaxSuccess event and store the url from the request in the callback: http://api.jquery.com/ajaxSuccess/
This is my suggestion:
PHP + Javascript Implementation:
In PHP, use $_GET['curr'] and $_GET['cat'] to retrieve the arguements from the URL.
Use $_SESSION['curr'] = $_GET['curr']; to save them per the session.
On your Javascript/jQuery use var curr = "<?php echo $_SESSION['curr']; ?>" to make the PHP session variables available to your Javascript.
Basically the key to have a good PHP/Javascript persistent memory is that you can set PHP content into a Javascript variable by using:
var x = <?php echo '123';?>;
console.log(x); //output '123' to Javascript console
If you need to have a list of all visited urls, you can save them in a PHP array and transfer it to Javascript as well.
On PHP side:
if (!isset($_SESSION['visited'])) $_SESSION['visited'] = array();//initialize the array if doesn't exist
if (!inarray( $_SERVER['REQUEST_URI'], $_SESSION['visited']) { //check if current URL is not in array
$_SESSION['visited'][] = $_SERVER['REQUEST_URI'];//push it to the array
}
On Client side:
//this will convert the PHP array to a Javascript array using json_encode
var visited_urls= <?php echo json_encode($_SESSION['visited']); ?>;
Don't forget to use session_start() on every page you need the session variables.
Javascript Only Implementation:
Use localStorage and keep everything on the client side.
EDIT: Note that localStorage is only supported in IE8 and up, so if versions prior to IE8 must be supported, you will need to use Cookies instead of localStorage.
$(document).ready(function() {
var urls = JSON.parse(localStorage["visited"]) || [];//get the visited urls from local storage or initialize the array
if (urls.indexOf(document.URL) == -1) {//if current url does not exist in the array
urls.push(document.URL);//add it to the array
localStorage["visited"] = JSON.stringify(urls);//save a stringifyed version of the array to local storage
}
});
Hope this helps!
It's unclear what you want to achieve with this feature. You state:
Users can click around my app and apply different filters and scrolls through pages and I need some way of tracking this so that I always know what data has already been loaded for that users session.
What do you want to achieve with this, why isn't the browser's cache enough for you?
My idea for a solution would be to sync server session array with an object inside the Browser via some sort of WebSocket (http://en.wikipedia.org/wiki/WebSocket).
UPDATE2:
It is possible to use localStorage as cache storage as Abel Melquiades Callejo suggests and then read from it bypassing HTTP requests. I would choose what content to save to that cache differently, no server involved:
add a custom attribute data-* to every HTML element you want cached (http://html5doctor.com/html5-custom-data-attributes/);
make a querySelectorAll (https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll) for all HTML elements with that attribute;
storing and retrieving documents from localStorage should be easy now, you need a convention for naming files for easy finding;
storing images implies doing a base64 transformation which increases the size of the data by 34% (image with 64kb will take 86kb in localStorage).
you need a way to find when data in localStorage is obsolete and you need to make requests to the server (perhaps another data-age attribute to specify when should it expire).
However, this localStorage solution is limited to a small amount of data, see this issue https://github.com/RemoteStorage/remoteStorage.js/issues/144. So, although I now see that what you are asking is possible, because of this size limitation to localStorage, I strongly recommend the solutions in my UPDATE1, below.
UPDATE1: The point is that caching mechanisms are incredibly complex. A better alternative would be to use the default browser caching mechanisms:
1. HTML5 cache manifest
Go offline with application cache
http://html5doctor.com/go-offline-with-application-cache/
LET’S TAKE THIS OFFLINE http://diveintohtml5.info/offline.html
Using the application cache
https://developer.mozilla.org/en/docs/HTML/Using_the_application_cache
A Beginner's Guide to Using the Application Cache http://www.html5rocks.com/en/tutorials/appcache/beginner/
2. Server's response headers to HTTP requests
Optimize caching - Leverage browser caching
https://developers.google.com/speed/docs/best-practices/caching#LeverageBrowserCaching
HTTP Caching FAQ https://developer.mozilla.org/en/docs/HTTP_Caching_FAQ

Using XMLHTTPRequest to extract data from Database

I want to extract some data from the database without refreshing a page. What is the best possible way to do this?
I am using the following XMLHTTPRequest function to get some data (shopping cart items) from cart.php file. This file performs various functions based on the option value.
For example: option=1 means get all the shopping cart items. option=2 means delete all shopping cart items and return string "Your shopping cart is empty.". option=3, 4...and so on.
My XHR function:
function getAllCartItems()
{
if(window.XMLHttpRequest)
{
allCartItems = new XMLHttpRequest();
}
else
{
allCartItems=new ActiveXObject("Microsoft.XMLHTTP");
}
allCartItems.onreadystatechange=function()
{
if (allCartItems.readyState==4 && allCartItems.status==200)
{
document.getElementById("cartmain").innerHTML=allCartItems.responseText;
}
else if(allCartItems.readyState < 4)
{
//do nothing
}
}
var linktoexecute = "cart.php?option=1";
allCartItems.open("GET",linktoexecute,true);
allCartItems.send();
}
cart.php file looks like:
$link = mysql_connect('localhost', 'user', '123456');
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('projectdatabase');
if($option == 1) //get all cart items
{
$sql = "select itemid from cart where cartid=".$_COOKIE['cart'].";";
$result = mysql_query($sql);
$num = mysql_num_rows($result);
while($row = mysql_fetch_array($result))
{
echo $row['itemid'];
}
}
else if($option == 2)
{
//do something
}
else if($option == 3)
{
//do something
}
else if($option == 4)
{
//do something
}
My Questions:
Is there any other way I can get the data from database without
refreshing the page?
Are there any potential threats (hacking, server utilization,
performance etc) in my way of doing this thing? I believe a hacker
can flood my server be sending unnecessary requests using option=1,
2, 3 etc.
I don't think a Denial of Service attack would be your main concern, here. That concern would be just as valid is cart.php were to return HTML. No, exposing a public API for use via AJAX is pretty common practice.
One thing to keep in mind, though, is the ambiguity of both listing and deleting items via the same URL. It would be a good idea to (at the very least) separate those actions (or "methods") into distinct URLs (for example: /cart/list and /cart/clear).
If you're willing to go a step further, you should consider implementing a "RESTful" API. This would mean, among other things, that methods can only be called using the correct HTTP verb. You've possibly only heard of GET and POST, but there's also PUT and DELETE, amongst others. The reason behind this is to make the methods idempotent, meaning that they do the same thing again and again, no matter how many times you call them. For example, a GET call to /cart will always list the contents and a DELETE call to /cart will always delete all items in the cart.
Although it is probably not practical to write a full REST API for your shopping cart, I'm sure some of the principles may help you build a more robust system.
Some reading material: A Brief Introduction to REST.
Ajax is the best option for the purpose.
Now sending and receiving data with Ajax is done best using XML. So use of Web services is the recommended option from me. You can use a SOAP / REST web service to bring data from a database on request.
You can use this Link to understand more on Webservices.
For the tutorials enough articles are available in the Internet.
you're using a XMLHttpRequest object, so you don't refresh your page (it's AJAX), or there's something you haven't tell
if a hacker want to DDOS your website, or your database, he can use any of its page... As long as you don't transfer string between client and server that will be used in your SQL requests, that should be OK
I'd warn you about the use of raw text response display. I encourage you to format your response as XML or JSON to correctly locate objects that needs to be inserted into the DOM, and to return an tag to correctly handle errors (the die("i'm your father luke") won't help any of your user) and to display them in a special area of your web page
First, you should consider separating different parts of your application. Having a general file that performs every other tasks related to carts, violates all sorts of software design principles.
Second, the first vulnerability is SQL injection. You should NEVER just concatenate the input to your SQL.
Suppose I posted 1; TRUNCATE TABLE cart;. Then your SQL would look like:
select itemid from cart where cartid=1; TRUNCATE TABLE cart; which first selects the item in question, then ruins your database.
You should write something like this:
$item = $_COOKIE['cart'];
$item = preg_replace_all("['\"]", "\\$1", $item);
To avoid refreshing, you can put a link on your page. Something like, Refresh
In terms of security, it will always pay to introduce a database layer concerned with just your data, regardless of your business logic, then adding a service layer dependent on the database layer, which would provide facilities to perform business layer actions.
You should also take #PPvG recommendation into note, and -- using Apache's mod_rewrite or other similar facilities -- make your URLs more meaningful.
Another note: try to encapsulate your data in JSON or XML format. I'd recommend the use of json_encode(); on the server side, and JSON.parse(); on the client side. This would ensure a secure delivery.

Categories

Resources