I am trying to make the code for a shopping cart, which is working. However, when I refresh the page it's adding a product to my cart automatically.
For example, I have 3 products on my website, which are Apple, Banana, Orange.
I click on Apple and it's added to my cart with QTY 1 and the URL is showing
`mydomain.com/my-cart?action=addcart&p_id=FylvGt6Yyb6n%2BzTXcJHwjBawOY%2Fw3QSZxF7rdUJLqhA%3D#`
Now if I refresh the page then it's adding another Apple to my cart (QTY 2). Then if I refresh the page again it adds another Apple (QTY 3) and so on. I don't know why this is happing. It's adding to SESSION.
Would you help me in this?
Below Is my cart code.
$action = isset($_GET['action'])?$_GET['action']:"";
$p_id=$conn->real_escape_string($_GET['p_id']);
$decrypted_p_id = decryptIt($p_id);
//Add to cart
if($action=='addcart') {
//Finding the product by code
$query = "SELECT p_unique_id, p_images,p_name, p_currentprice FROM products WHERE p_id=?";
if ($stmt = $conn->prepare($query)) {
$stmt->bind_param("i", $decrypted_p_id);
$stmt->execute();
$stmt->bind_result($p_unique_id,$p_images, $p_name, $p_currentprice);
$stmt->fetch();
}
$currentQty = $_SESSION['products'][$decrypted_p_id]['qty']+1; //Incrementing the product qty in cart
$_SESSION['products'][$decrypted_p_id] =array(
'qty'=>$currentQty,
'p_unique_id'=>$p_unique_id,
'p_images'=>$p_images,
'p_name'=>$p_name,
'p_currentprice'=>$p_currentprice
);
$product='';
// header("Location:cart.php");
}
Displaying product
<?php if(!empty($_SESSION['products'])):
foreach($_SESSION['products'] as $key=>$product):?>
/*some code here*/
endforeach;?>
<?php endif;?>
Edited code here Suggested by ADyson
if (isset($_POST['submit'])) {
$action=$conn->real_escape_string($_POST['action']);
$decrypted_p_id=$conn->real_escape_string($_POST['p_id']);
// whole code here
i found this code:
$currentQty = $_SESSION['products'][$decrypted_p_id]['qty']+1;
this code always run when u reload the page,
give some condition if you want to add manually
If you simply click refresh on the exact same page then action=addcart etc. is still in the URL. Therefore inevitably it runs that action again when the page loads, and adds the items to the cart again.
An "add" action like that would be better done as a POST request, partly for semantic reasons (it's "sending" data rather than "get"ting it) and partly to avoid annoyances like this. Ideally a GET request should not cause any change of state in the application.
Instead of
Add to cart
you can do something like:
<form action="my-cart" method="POST">
<button type="submit">Add to cart</button>
<input type="hidden" name="action" value="addcart"/>
<input type="hidden" name="p_id" value="<?php echo $p_user_id;?>"/>
</form>
You can use some CSS to make the button appear more like your old hyperlink, if you wish.
Then, in your PHP cart code, simply replace all references to $_GET with $_POST instead, to read the values from the POST request.
This will have the advantage that the variables are not saved into the URL and therefore if someone tries to refresh the URL it will not automatically repeat the same action based on those variables.
You could also look into sending the data to add cart items via AJAX, so that it doesn't require a postback at all and usually results in a smoother user experience - if you look at most shopping websites now, that is generally what they do.
Related
I am making a page with soccer teams and leauges. Now i`m printing all Leagues that i want from the database.
League 1
League 2
League 3
etc.
As you can see each League has its own League_ID. In Database i also have a table of all teams, and each team has matched League (with League_ID). I also have a view, where i can print table of League that i want. This function in php looks like this.
public function leauge_table(){
$tables = $this->scoreTableRepository
->getScoreTable(1);
//TODO how to change this "1" static to generated
//TODO when pressing link
return $this->render('leauge_table', ['table' => $tables]);
And as you can see, when i go to this page i will always see the score table from leauge that has id=1.
And the question is how can i make that when i press for example at "League 2" i will open page but with table matching to League_ID = 2. Shall it be <button></button> or <a></a> in HTML. And how to pass there League_ID so my php back will see which table should render.
Thank you really for help.
PS
Or maybe do i have to make a seperate view for each leauge score table? And then just simply make buttons direct to these views with simple JS code. But would like to avoid it if it`s possible.
It can be a link or a button. A link with the league ID as a parameter in the URL is the simplest approach though, if you're new to the concept. e.g.
League 1
The ID would then be available in the php script via $_GET["id], once the link is clicked.
In your SoccerTeam page add a button in a form with the following :
<form action="youpage.php" method="post">
<input name="leagueId" type="hidden" value="<?php echo $leagueId;?>" >
</form>
And in order to process that information, since we passed an id, we can retrieve it with $_POST['leagueId'] and because it's a POST request it wont be visible in the url:
$leagueId = $_POST['leagueId'];
I got this opensource php mini cart from youtube. Now the problem is how to apply it with ajax or javascript? So that everytime I add, remove and delete the items it wont refresh the whole page and will still work whether the javascript is on or off. If javascript is on the cart.php will use javascript and if it is off the cart.php will use php.
here's the code for add, remove and delete items in the cart. To look or download the full source code just click this link: cart php source code
if(isset($_GET['add'])){
// use session to add the product
$quantity = mysql_query('SELECT id, quantity FROM products WHERE id='.mysql_real_escape_string((int)$_GET['add']));
while($quantity_row=mysql_fetch_assoc($quantity)){
//if quantity is not equal in the database quantity
if ($quantity_row['quantity']!=$_SESSION['cart_'.(int)$_GET['add']]){
$_SESSION['cart_'.(int)$_GET['add']]+='1';
}
}
header('Location: '.$page);
}
if(isset($_GET['remove'])){
$_SESSION['cart_'.(int)$_GET['remove']]--;
header('Location: '.$page);
}
if(isset($_GET['delete'])){
$_SESSION['cart_'.(int)$_GET['delete']]='0';
header('Location: '.$page);
}
It is very simple to implement ajax in opencart. you just need to use it's own prebuilt Cart API and use it in your project.
First need to learn URL for Cart Functionalities
1. http:/ /< project location >/index.php?route=checkout/cart/add (with product_id and quantity as parameters)
2. http:/ /< project location >/index.php?route=checkout/cart/remove (with key as parameter which is cart id)
3. http:/ /< project location >/index.php?route=checkout/cart/edit (quantity[key] and value = 'quantity' as parameters
now you can use these code in Ajax requrest, assuming that your using jquery
var cart = {
'add':function(product_id){
$.get('http:/ /< project location >/index.php?route=checkout/cart/add',
{product_id: product_id},
function(data){}
},
};
Like this you can make add, remove, edit and getcart function and you can add these functions to buttons or page load etc.
for example
<button onclick="cart.add('prod_01');> Add to Cart </button>
Please Note
these routes are basic opencart structure so no need to change it, you just have to use these routes in your javascript code to make ajax call and display the result, it's output is in JSON format, so it is very simple and easy to display a cart.
Good Luck
I did some research already but can't find a good solution to this. I am sure it's simple, but I could use some help.
I am using HTML -> Javascript -> PHP to get info back from a database.
My goal is to have the data return, but have it add check boxes at the end of each row where if the person check it, it will add them to another table.
In my example, it will return a list of cards and if the person uses the check box it will add each card they checked to a "have" list. For my code provided below, it's a "display all" so I didn't use any javascript. I put it straight from html to php. I figure if I can get the most simple example working, adding the js to my other search display will be easy.
HTML
<fieldset>
<form action="display_all.php" method="post">
Order by: <select name="order_all" id="order_all">
<option value="parallel">Parallel</option>
<option value="faction">Faction</option>
</select>
<input type="submit" value="display all cards">
</form>
</fieldset>
PHP (to save space I cut out some of the standard code)
$order_all = $_POST['order_all'];
// Create SQL statement
$query = "SELECT * FROM cards ORDER BY $order_all ASC";
// Execute SQL statement
if (!($result = # mysql_query ($query, $connection)))
showerror();
// Display results
while ($row = # mysql_fetch_array($result)) {
echo "<tr><td>{$row["parallel"]}</td>
<td>{$row["faction"]}</td>
<td>{$row["in_set"]}</td>
<td>{$row["card_name"]}</td>
<td>{$row["color"]}</td>
<td>{$row["number_in_set"]}</td>
<td>{$row["rarity"]}</td>
<td>{$row["sold_out"]}</td>
<td>{$row["series"]}</td>
</tr>";
}
I tried adding different things to the while { } at the end of the PHP file but I don't really know the proper way to do that. Based on what I saw around, people suggest doing this in javascript and creating a function for it. Start with my ajax call and callback? I planned on linking my checkboxes to the ID of each card (which is stored in the database, but not printed) I figure they will just be linked to query insert commands. Like if check [ insert command ] and form submit? idk looking for some suggestions, I am still new to using databases in this sort of way.
FOUND A SOLUTION TO MY PROBLEM, well sorta.
It was a bunch of little things. I haven't added functionality, but I at least got the checkbox to show up.
while ($row = # mysql_fetch_array($result)) {
echo"
<tr>
<td>{$row["parallel"]}</td>
<td>{$row["faction"]}</td>
<td>{$row["in_set"]}</td>
<td>{$row["card_name"]}</td>
<td>{$row["color"]}</td>
<td>{$row["number_in_set"]}</td>
<td>{$row["rarity"]}</td>
<td>{$row["sold_out"]}</td>
<td>{$row["series"]}</td>
";
echo'<td><input type="checkbox" value="submit" id="{$row["id"]}/></td>';
echo"</tr>";
}
Your code is paradise for SQL injection! You have to check user input, at least escaping with mysql_real_escape_string or
Switch to newer, better and safer mysqli (or PDO) interface and use prepared statements. I recommend mysqli anyway.
Note: in this particular case is best to use switch with options.
To question: why don't you get checkbox value from post and then take actions, but I'm not sure what are you asking.
I am using the php code to empty my cart on my website if javascript is disabled. Only problem is that it empties the cart but submit the page too. I want it to remain on the same page and empty the cart because the page is supposed to submit for checking out not emptying the cart. Also I can't use javascript for this part because this is meant for user's who don't have javascript enabled.
I have tried using:
return false;
in the post function but it just made the page blank.
Here is my code:
<form method='post' action='checkout.php'>
// some input
<input type='submit' id='cart-empty' name='cartEmpty' value='Empty' />
</form>
if($_POST['cartEmpty']) {
$this->shippingfee = 0;
$this->empty_cart();
}
You mentioned in one of the comments that you weren't able to modify the headers (i.e. header('Location: form.php); because the header information has already been sent. To get around this, you should move your check for the posted cartEmpty value to the top of your submit page.
Headers are delivered any time content is echoed out to the browser (even white space such as blank lines), but if you do this processing prior to any output being sent, you have an opportunity to modify those headers still:
<?php
if($_POST['cartEmpty']) {
$this->shippingfee = 0;
$this->empty_cart();
header("Location: cartEmptied.php");
exit();
}
You can use this php code for validation in checkout.php and return user to page(if user doesn't fill the form):
if(empty($_POST['cartEmpty'])){
header("Location: ./form.php");
die;
}
So I'm trying to create a webpage where the user puts in there course information. There is an add button on the page, that adds another text field for them if they need more fields.
Once the Add button is pressed, the page is reset and all of the information that has been previously entered is gone. I could save the information in an array, and when or if the the add button is pressed save the information into an array, and re populate the fields using what was stored in the array.
My question is: Is there a way to refresh a page, and keep the information in the text fields, without taking the long process mention above, is there some attribute that I can use that will not delete information that has been previously entered into ?
If you code HTML5, you can use localStorage with a fallback to cookies. Also, if the information should be removed after session end, then you may use sessionStorage instead.
You can use ajax i think...it runs in background no page reload is done.
Assuming this HTML:
<form id="course-info-form" action="submit-course-info.php" method="post">
Professor name: <input type="text" name="professor"><br>
Additional info:<br>
<input type="text" name="additional0"><br>
<input type="submit" value="Submit">
</form>
<br>
<button id="add-button">Add Field</button>
<!-- Use jQuery for DOM manipulation -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
With JavaScript / jQuery:
var courseInfoForm = $('#course-info-form');
var addButton = $('#add-button');
// Keep track of how many fields there are, so each can have a unique "name" attribute
var additionalFieldsAdded = 1;
// Whenever "Add Field" is clicked, create another input field
addButton.on('click', function() {
var newInput = $("<input>", {
type: "text"
name: "additional" + additionalFieldsAdded
});
courseInfoForm.append(newInput, "<br>");
additionalFieldsAdded += 1;
});
I'm not very good at PHP. In your PHP script, make a while loop that checks to see if isset($_POST['additional0']), and additional1, additional2, etc, until you are sure that there were no more additional fields passed. Then store all those additional details into an array, and handle it how you see fit.
As for your original question, I recommend using my solution instead. It's better to avoid unnecessarily reloading the page, if all you're doing is simply adding a new form each time.
I suppose you could capture the information that was "tentatively-submitted" when the "Add Field" button is clicked, and then in your PHP script loop through all the additional fields and create 1 more input element each time another field is added, and set the value attribute of each "old" input element to whatever was "tentatively-submitted."
So, to answer your question, you can set the default value of an input field (server-side) with:
// add-course-information.php
<?php
$addingField = false;
// Check for the optional "?do=addfield" parameter
if (isset($_POST['do']) && $_POST['do'] == 'addfield') {
$addingField = true;
$fields = array();
$nextField = 'additional' . count($fields);
// Get each piece of POSTed field data
while (isset($_POST[$nextField]) && $_POST[$nextField] != '') {
array_push($fields, $_POST[$nextField]);
$nextField = 'additional' . count($fields);
}
}
?>
<!-- Silly HTML! -->
<?php
// If adding a field, recreate and repopulate all previous fields
if ($addingField) {
for ($i = 0; i < count($fields); i++) { ?>
<input type="text" name="additional<?= $i ?>" value="<?= $fields[$i] ?>">
<?php } ?>
<input type="text" name="additional<?php echo count($fields) + 1 ?>">
<?php }
// Otherwise, show the default additional field
else { ?>
<input type="text" name="additional0">
<?php } ?>
<!-- More awesome HTML! -->
That might work... (Currently untested.)
What that page is supposed to do (if it works) is:
On default, give the user his initial setup, with just 1 additional input field, "additional0".
When the user clicks "Add Field," ?do=addfield should be POSTed to add-course-information.php (you can write that part), and when this page receives the do=addfield parameter, then it knows to loop through all the submitted additional fields, and store them each into an array, and then afterwards output all the submitted data back into another loop's-worth of dynamically generated <input> elements.
But I think that that would be much more complicated, and unnecessarily increase the processing your server has to do. It could even be abused if someone was to hammer the "Add Field" button hundreds of thousands of times a minute, eventually making your for-loops iterate millions of times... (Unless you imposed a limit on the maximum number of fields, which would be easy.)
However, you might as well leverage the client's processing power if it's available.