I am developing a eCommerce website in php without any cms. I have done approx all things, but I am facing a problem in add to cart page. I want to display a successfully message after add to cart with session variable. Please suggest me.
Here is my code:
<?php
session_start();
include('dbfunctions.php');
$id = $mysqli->real_escape_string($_GET['id']);
$category_id=$mysqli->real_escape_string($_GET['category_id']);
?>
<?php
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
$products=$mysqli->query("select * from product_details where id=$id and category_id='$category_id'");
if(count($products)>0)
{
$obj=$products->fetch_object(); {
echo '<form method="post" action="cart_update.php">';
echo '<img src="../image/product/'.$obj->pic.'"class="img-responsive" style="width:100%;height:300px;">';
echo ucwords($obj->product_name);
echo $obj->material;
echo $obj->product_code;
echo $obj->area;
echo $obj->width;
echo $obj->rolls;
echo $obj->features;
echo '<button id="button-cart">Add to Cart</button>';
echo '<input type="hidden" name="id" value="'.$obj->uid.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
}
}
?>
mysqli_query Returns FALSE on failure and for successful queries if will return TRUE. You can't use it for count
So instead of this
$products=$mysqli->query("select * from product_details where id=$id and category_id='$category_id'");
if(count($products)>0)
you need to count number of rows
$row_cnt = $products->num_rows;
if(count($row_cnt)>0)
if ($success){
$message = "Sent! Thank you";
} else {
$message = "Ops! Try again!";
}
?><script>
prompt(<?php echo json_encode($message); ?>);
</script>
<noscript>
<p><?php echo htmlspecialchars($message); ?></p>
</noscript>
Note: Given a string for input, json_encode will output a JavaScript string literal that is safe for inclusion in an HTML script element. It will not output JSON.
While the strings themselves don't contain any special characters, it is a good habit to run this sort of XSS protection against anything you output that isn't explicitly HTML/JS/etc.
Or try this
<?php
if ($success) {
$message = "Added! Thank you.";
} else {
$message = "Oops...";
}
echo '<div id="message">'.$message.'<div id="close-button"></div></div>';
?>
This way you can style your message like you want to (like positioning it absolutely). But you would have to implement the close button in javascript if the div is positioned absolute. I hope this helps
For display this type message toast is fit to your requirement.
http://codeseven.github.io/toastr/demo.html
You could use jQuery for this and ajax to your page as such:
jQuery
var itemName = $( "#itemName" ).val(); //Get the value using the ID of the input
var itemPrice = $( "#itemPrice" ).val(); //Get the value using the id of the input
$.ajax( {
url: "myphpscript.php?itemName=" + ietmName + "&itemPrice=" + itemPrice, //Specify your url to go to (an abosulte path to the php script to run)
type: "GET", //Specify the type, can be GET or POST
success: function ( response ) //Set the success function
{
if (response == "true") //Check the response it "true"
{
alert( "Item addded to cart!" ); //Show success message
return;
}
//response == "false" handler
alert( "Failed to add item to the cart" ); //Show fail message
return;
}
} );
PHP CODE
function addToCart()
{
if (!isset($_REQUEST['itemName']) || !isset($_REQUEST['itemPrice']))
{
return "false";
}
//Add to cart code with `return "true";` or `return "false"` checks
return "true";
}
I hope this goes some way to helping you :)
Related
Once we click on Download button, we are trying to download complete order details in pdf.... here 100452121 is orderid, xpress is shipping name & 14104918100111 is tracking id....
we set conditions that if tracking_id is empty, than it should echo 0 but we are getting zero [0] even when tracking_id available for the order....
Shippinglabel.php Full code in pastebin
<td><?php echo $orderrecords[$k]["order_id"]; ?><br/>
<?php
if ($st == 1) {
if ($orderrecords[$k]["tracking_id"] == '') {
?>
<input type="button" name="shipment" id="xpress" value="xpress"
onclick="createshipment('<?php echo $orderrecords[$k]["order_id"];?>')" />
<?php
}
}
?>
<?php
if ($orderrecords[$k]["tracking_id"] != '' && $orderrecords[$k]["shipping_name"] == 'xpress')
{
?>
<a target="_blank"
href="http://sbdev1.kidsdial.com/ecom1/xpress/xpressdownload.php?orderId=<?php
echo $orderrecords[$k]["order_id"];?>"
id="pdfdownload" >
<input type="button" name="shipment" value="DOWNLOAD" /></a>
<?php
}
?>
</td>
createshipment
function createshipment(orderid)
{
var assignee='<?php echo $_SESSION['login_user']?>';
alert(orderid);
$.ajax({
url: "xpressshipment.php",
type: "POST",
data:'orderid='+orderid+'&assignee='+assignee,
success: function(data){
if(data==1)
{
$("#pdfdownload").show();
}
if(data==0){alert("First Enter Tracking Id.");}
window.location ="http://sbdev1.kidsdial.com/ecom1/xpress/xpressdownload.php?orderId="+orderid;
}
});
}
xpressshipment.php Full code in pastebin
<?php
$data =
array (
'AirWayBillNO' => $resultc[0]['awb'],
);
if($res->AddManifestDetails[0]->ReturnMessage=='successful')
{
$sqli="update do_order set tracking_id='".$resultc[0]['awb']."',shipping_name='xpress' where order_id='".$order_id."'";
$resulti=$db_handle->executeUpdate($sqli);
}
?>
xpressdownload.php Full code in pastebin
<?php
if(isset($_GET['orderId']) && $_GET['orderId']!='')
{
$orderid=$_GET['orderId'];
}
else
{
echo 2;
}
$orderid='';
$sqlorder = "SELECT tracking_id,order_id from do_order where order_id='".$orderid."' limit 1";
$resultdoorder = $db_handle->runSelectQuerys($sqlorder);
if($resultdoorder['tracking_id']=='')
{
echo 0;
//var_dump("tracking_id");
}
var_dump("tracking_id"); gave string(11) "tracking_id" as result....
please let me know if you need more details....
please help me to find solution....
Thanks in Advance....
In file xpressdownload.php you defined variable $orderid incorrectly.
if(isset($_GET['orderId']) && $_GET['orderId']!='')
{
$orderid=$_GET['orderId'];
}
else
{
echo 2;
}
$orderid='';
First, you are checking whether $_GET['orderId'] exists and if yes, you give the value of $_GET['orderId'] to $orderid. This is correct.
But after the if... else block you give the $orderid the '' value. So in every case the $orderid has the null value and you sql query is not returning the record. You have to remove the line $orderid=''; or move it before the if statement.
This is the snippet in my index:
<p id="text" style="display:none">hello</p>
echo '<tr>';
echo '<td>'.$s['school_name'].'</td>';
echo '<td>'.$s['location'].'</td>';
echo '<td>'.$s['population'].'</td>';
echo '<td>'.$s['cost'].'</td>';
echo '<td>'.$s['topnotchers'].'</td>';
echo '<td>'.$s['rating'].'</td>';
echo '<td><input type="checkbox" name="userSelection" name="userSelection" onclick="userSelection()" value="'.$s['school_id'].'"</td>';
echo '</tr>';
}
And here is my js:
function userSelection(){
var checkBox = document.getElementsByName("userSelection")[0];
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
The text only displays when I check on row[0] since I set it to row[0]. But, what should be done if I need the function to be true to all rows when I check it?
The above code only displays text on first loop.
Is "*" going to work?
I'm a beginner, a help would be appreciated.
You have hard coded the index 0. So js function will run only for checkbox with zero index.
First of all change the name of checkboxes to checkbox1, checkbox2,... This will simplify the case.
Then You need to run a for loop for each checkbox. Use
`
for(i=0; i < 6; i++){
currentCheckBox = document.getElementById("checkbox"+i)
var text = document.getElementById("text");
if (currentCheckBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
`
You have to specify a name as an array like below,
<input type="checkbox" id="userSelection1" name="userSelection[]" onclick="userSelection()" value="">
Then only you can able to loop in javascript to check the status
var checkBoxArr = document.getElementsByName("userSelection[]");
<?
//LUHN ALGORITHM PHP CONVERSION
// CREDIT CARD NUMBER CHECKER BY JACK BELLAMY - JACKBELLAMY.CO.UK
//----------- RETREIVE THE STRING FROM THE FORM POST -------------//
$var = $_POST['cardnumber'];
//----------- SPLIT THE 16 CHARACTOR STRING INTO INDIVIDUAL CHARACTERS AND ASSIGN TO INDIVIDUAL VARIABLES ---------------//
$n0 = $var[0];
$n1 = $var[1];
$n2 = $var[2];
$n3 = $var[3];
$n4 = $var[4];
$n5 = $var[5];
$n6 = $var[6];
$n7 = $var[7];
$n8 = $var[8];
$n9 = $var[9];
$n10 = $var[10];
$n11 = $var[11];
$n12 = $var[12];
$n13 = $var[13];
$n14 = $var[14];
$n15 = $var[15];
// ---------------------CHECKING THE CARDNUMBER FORM POST SUBMITS ALL VALUES PROPERLY
/*
echo $n0;
echo $n1;
echo $n2;
echo $n3;
echo $n4;
echo $n5;
echo $n6;
echo $n7;
echo $n8;
echo $n9;
echo $n10;
echo $n11;
echo $n12;
echo $n13;
echo $n14;
echo $n15;
*/
//-------ASSIGNING THE NEW VARIABLE VALUES ------------//
$n14_new = ($n14*2);
$n12_new = ($n12*2);
$n10_new = ($n10*2);
$n8_new = ($n8*2);
$n6_new = ($n6*2);
$n4_new = ($n4*2);
$n2_new = ($n2*2);
$n0_new = ($n0*2);
//!-----!------!//
//------------------------TESTING WITH THE NEW VARAIBLE *2
/*
echo $n0_new;
echo $n1;
echo $n2_new;
echo $n3;
echo $n4_new;
echo $n5;
echo $n6_new;
echo $n7;
echo $n8_new;
echo $n9;
echo $n10_new;
echo $n11;
echo $n12_new;
echo $n13;
echo $n14_new;
echo $n15;
*/
//--------- THE MATHS FOR THE COMPLETE SUM ------------ //
$isitlegit = ($n0_new+$n1+$n2_new+$n3+$n4_new+$n5+$n6_new+$n7+$n8_new+$n9+$n10_new+$n11+$n12_new+$n13+$n14_new+$n15);
//!----MATHS-----!//
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="veri-styles.css"
</head>
<body>
<div class="container">
<div class="main-wrapper">
<div id ="verification-wrapper">
<form action="" method="post" enctype="application/x-www-form-urlencoded">
<div id="input-holder">
<input name="cardnumber" type="text" class="input-style" placeholder=""> </input>
<button class="button-style">Verify my card</button>
</div>
</form>
<div class="result-class">
<?php
if(isset($isitlegit) && ($isitlegit % 5 == 0)) { // it's good
$new = "<img src='correct.jpg' />";
} elseif(isset($isitlegit) && ($isitlegit % 5 != 0)) { // it's bad
$new = "<img src='incorrect.jpg' />";
} elseif(!isset($isitlegit)) { // make sure this is not set
$new = "<img src='card-number-required.jpg' />";
}
echo $new;
?>
</div>
</div>
</div>
</body>
</html>
You have three states you need to account for, 'open', 'correct', and 'incorrect' To do that you start with an 'open' state.
$new = "<img src='please_enter your card number.jpg' />";
echo $new;
You would use that in the first condition of your test -
if(isset($var) && ($isitlegit % 5 == 0)) { // it's good
$new = "<img src='correct.jpg' />";
} elseif(isset($var) && ($isitlegit % 5 != 0)) { // it's bad
$new = "<img src='incorrect.jpg' />";
} else { // the default view
$new = "<img src='please_enter your card number.jpg' />";
}
echo $new;
Once submitted you can only have one of two states, never to return to the default.
In addition you have left your stylesheet declaration un-closed. Please change it to this -
<link rel="stylesheet" type="text/css" href="veri-styles.css" />
if(false===$submitted){
echo "Please type your card details here";
} else {
if($isitlegit % 5 == 0) {
$new = "<img src='correct.jpg' />";
echo $new;
}
else {
$new = "<img src='incorrect.jpg' />";
echo $new;
}
}
The best way I can think of to achieve this is with AJAX. Create a div on your page where your initial message is displayed, and then use an AJAX call to submit the form data to a script you'll use to validate it, and within that script, echo either a "Success! Your card has been verified" or a "Unable to validate your card" message. Then have your AJAX function change the .innerHTML of the div to the responseText element. You can see this answer for a good starting point, as well as a note about using the jQuery library to simplify your AJAX implementation.
Edit: In response to another user's downvote, here's some code.
First, let's give your HTML form a call to an AJAX object we'll create. So change your HTML form code to this:
<form onSubmit="return process()">
process() is a javaScript function we're going to set up later with the AJAX call. You already have a div established where you want this data to appear, but we need to give it an id, so change:
<div class="result-class">
please enter your card number<img src='correct.jpg' />
</div>
to this:
<div class="result-class" id="result">
Please enter your card number.
</div>
And also assign an id to your text input:
<input name="cardnumber" type="text" class="input-style" placeholder="" id="cardnumber"> </input>
Now we'll create the javaScript function. (This is easier with jQuery, but I wrote it in plain javaScript so you won't need the dependancy if you're not familiar with how to use jQuery.
function process(){
var xmlhttp = new XMLHttpRequest();
var cardnumber = document.getElementById("cardnumber").value;
var result = document.getElementById("result");
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
result.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","validate.php?cardnumber=" + cardnumber,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
return false;
}
Now, use whatever php script you were going to use to validate the cc# and save it as a separate script called validate.php Use $_GET['cardnumber'] variable to fetch the cardnumber data sent from the form, run it through whatever validation process you are using. Use an if statement to create the responseText element for our AJAX function. You might have your script set some variable to boolean true or false to check this. I'll use $validated here.
if($validated){
echo 'Your card has been verified!';
} else {
echo 'Unable to validate your card.';
}
The AJAX function will change the text inside the "result" div to whatever text is echoed by your validate.php script.
This should get you on the right track, barring any syntax errors, I just wrote this all off the cuff.
Can i write some code to execute while my check box is checked in my php code..
my declaration of check box is...
<input id="checkbox" name="click" type="checkbox" onclick="check(this)"/>
i thought to perform a function called check() while clicking the check box..
<script type="text/javascript">
function check(cb)
{
if($("input[type=checkbox]:checked"")
{
//my functionality and operations
}
}
But its not working, how can i perform the onclick event in the Checkbox's action..
First of all, there's a mistake. It should be .is(":checked").
function check(cb)
{
if($(cb).is(":checked"))
{
//my functionality and operations
}
}
And the HTML should be:
<input type="checkbox" onclick="check(this);" />
Or, if you wanna invoke a PHP Function after clicking on Checkbox, you need to write an AJAX code. If this is the case, in your if condition, and checked condition, you can call a PHP file, that calls only this function.
function check(cb)
{
if($(cb).is(":checked"))
{
$.getScript("clickCheckbox.php");
}
}
And you can write JavaScript plus PHP in the clickCheckbox.php file, say something like this:
clickCheckbox.php
<?php
header("Content-type: text/javascript");
unlink("delete.png");
echo 'alert("Deleted!");';
?>
Once you click on the checkbox, and if the state is checked, it gives out an AJAX call to this PHP file, where you are deleting a file delete.png and in the echo statement, you are outputting a JavaScript alert, so that you will get an alert message saying Deleted!.
$('#myform :checkbox').click(function() {
var $this = $(this);
// $this will contain a reference to the checkbox
if ($this.is(':checked')) {
// the checkbox was checked
} else {
// the checkbox was unchecked
}
});
Where your form has id myform
use
if ($('#checkbox').is(':checked'))
or inside an event
$('#checkbox').click(function(){
if ($(this).is(':checked')){
//your routine here if checked
}else{
//routine here if not checked
}
});
You can put like this:
Include the column checked in your table with default value NO.
Then after your SELECT statement show the array.
page1.php
<input type=checkbox value="<?php $row['checked']?>" onclick="location.href = 'update.php?id=<?php echo $row['id']; ?>&checked=<?php if ($row['checked'] == 'YES') { ?>NO<?php } else {?>YES<?php } ?>';" <?php if ($row['checked'] == 'YES') { ?> checked <?php } ?>>
update.php
<?php include('server.php'); ?>
<?php
$id = $_GET['id'];
$checked = $_GET['checked'];
if(isset($_GET['id']))
{
$sql = "UPDATE table SET
checked = '$checked'
WHERE `id` = '$id' ";
if ($conn->query($sql) === TRUE)
{
}
else
{
echo "Error updating record: " . $conn->error;
}
header('location: page1.php');
}
?>
Try this one
<input id="checkbox" name="click" type="checkbox" onclick="check()"/>
//in js
if( $('input[name=checkbox]').is(':checked') ){
// your code
}
I'm trying to implement a form that utilizes jquery's post feature to dynamically update the database. What I'm realizing is that after the user clicks the "update" button, the success function is called back just fine with a "Update successful" message.
The issue I have for the stackoverflow world is why on subsequent clicks (w/o refreshing the page) I'm not getting this same success message. Also, ironically my database is being updated, so I know the AJAX call is going through.
I've posted my code below:
JS
var TEAM = {
update: function() {
var form_data = $('form').serialize();
$.ajax({
type: "POST",
url: "../manager/edit_team.php",
data: form_data,
error: function() {
$('#status').text('Update failed. Try again.').slideDown('slow');
},
success: function() {
$('#status').text('Update successful!');
},
complete: function() {
setTimeout(function() {
$('#status').slideUp('slow');
}, 3000);
},
cache: false
});
}
}
// jQuery Code for when page is loaded
$(document).ready(function()
{
$("#update").on("click", function() {
TEAM.update();
});
});
PHP (I welcome any other comments as well)
require '../includes/config.php';
include '../includes/header.html';
// autoloading of classes
function __autoload($class) {
require_once('../classes/' . $class . '.php');
}
// Site access level -> Manager
$lvl = 'M';
// Assign user object from session variable
if (isset($_SESSION['userObj']))
{
$manager = $_SESSION['userObj'];
}
else
{
session_unset();
session_destroy();
$url = BASE_URL . 'index.php';
ob_end_clean();
header("Location: $url");
exit();
}
// Establish database connection
require_once MYSQL2;
// Assign Database Resource to object
$manager->setDB($db);
// Authorized Login Check
if (!$manager->valid($lvl))
{
session_unset();
session_destroy();
$url = BASE_URL . 'index.php';
ob_end_clean();
header("Location: $url");
exit();
}
// Check for a valid game sch ID, through GET or POST:
if ( (isset($_GET['z'])) && (is_numeric($_GET['z'])) )
{
// Point A in Code Flow
// Assign variable from myteams-m.php using GET method
$id = $_GET['z'];
}
elseif ( (isset($_POST['z'])) && (is_numeric($_POST['z'])) )
{
// Point C in Code Flow
// Assign variable from edit_team.php FORM submission (hidden id field)
$id = $_POST['z'];
}
else
{
// No valid ID, kill the script.
echo '<p class="error">This page has been accessed in error.</p>';
include '../includes/footer.html';
exit();
}
$team = new ManagerTeam();
$team->setDB($db);
$team->setTeamID($id);
$team->pullTeamData();
$flag = 0;
echo $flag . "<br />";
// Confirmation that form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{ // Point D in Code Flow
// Assume invalid values:
$tname = FALSE;
// Validate team name
if ($_POST['tname'])
{
$tname = $_POST['tname'];
}
else
{
echo '<p class="error"> Please enter a team name.</p>';
}
// Validate about team information
if ($_POST['abouttm'])
{
$abtm = trim($_POST['abouttm']);
}
else
{
$abtm = '';
}
// Check if user entered information is valid before continuing to edit game
if ($tname)
{
if($team->editTeam($tname, $abtm) == True)
{
echo '<p>Team was successfully updated</p>';
$flag = 1;
}
else
{
echo '<p>No changes were made</p>';
$flag = 2;
}
}
else
{ // Errors in the user entered information
echo '<p class="error">Please try again.</p>';
}
} // End of submit conditional.
echo $flag . "<br />";
// Point B in Code Flow
// Always show the form...
// Get team name attribute
$team->pullTeamData();
$teamname = $team->getTeamAttribute('tmname');
$about = $team->getTeamAttribute('about');
if ($teamname != '') // Valid user ID, show the form.
{
// Headliner
echo '<h2>Edit Team</h2>';
// Create the form:
echo '
<div id="EditTeam"></div>
<div id="Team">
<fieldset id="TeamDetails">
<legend>Edit Team</legend>
<form method="post" id="information">
<p id="status"></p>
<input type="hidden" name="z" value="' . $id . '" />
<p>
<label for="tname">New Team Name:</label><br/>
<input type="text" name="tname" id="tname" size="10" maxlength="45" value="' . $teamname . '" />
</p>
<p>
<label for="abouttm">Team Information:</label><br/>
<textarea id="abouttm" name="abouttm" cols="30" rows="2">"' . $about . '"</textarea><br />
<small>Enter something cool about your team.</small>
</p>
<p>
<input type="hidden" name="id" id="id">
<input type="button" value="update" id="update" />
</p>
</form>
</fieldset>
</div>';
}
else
{ //Not a valid user ID, kill the script
echo '<p class="error">This page has been accessed in error.</p>';
include '../includes/footer.html';
exit();
}
// Close the connection:
$db->close();
unset($db);
include '../includes/footer.html';
?>
You'll notice I also have a $flag defined to help with the debugging, but ironically it outputs 0 no matter the number of clicks to the "update" button. So there's no indication that the database is being updated, yet when I check the tables it certainly is.
I appreciate any help or pointers. Thanks,
#status message is not showing because you've hidden it by slideUp(), to show it again you need to slideDown() them.
success: function() {
$('#status').text('Update successful!');
-ADD-> $('#status').slideDown('slow');
},
complete: function() {
setTimeout(function() {
$('#status').slideUp('slow');
}, 3000);
Do it same way as you have done in error handler:
success: function(){
$('#status').text('Update successful!').slideDown('slow');
...
It seems that you know it already and just forgot it...
Other method that may be useful is stop() to make sure that previous animation is stopped when new one is starting., especially important when using long timeouts/animations.
(useful = can prevent other problems with visibility and makes sure that messages does not start jumping in and out)
(long = somewhere around 0,5-1,5 sec or more, if during this time can happen something else then it is long...)
For example, this will clear fx queue, finish running animation immediately and slideUp():
$('#status').stop(true, true).slideUp('slow');
You also asked suggestions for other parts of code
If you are using same code at least twice or if it is general method that could be reused make it reusable:
function redirect_to( $page ) {
session_unset();
session_destroy();
$url = BASE_URL . $page;
ob_end_clean();
header("Location: $url");
exit();
}
if ($condition == true) {
redirect_to( 'index.php' );`
}