The application of Ajax in Shopping cart

Source: Internet
Author: User
Tags rowcount

The code is as follows:

Shopping Cart Page:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
<title> easy to buy network-home </title>
<link type= "Text/css" rel= "stylesheet" href= "Css/style.css"/>
<script type= "Text/javascript" src= "Scripts/jquery-1.8.3.min.js" ></script>

<body>
<div id= "header" class= "wrap" >
<div id= "logo" ></div>
<div class= "Help" ><a href= "shopping.html" class= "shopping" > Shopping cart x Pieces </a><a href= "login.html" > Login </a><a href= "register.html" > Register </a><a href= "guestbook.html" > Message </a><a href= " manage/index.html "> Admin </a></div>
<div class= "NavBar" >
<ul class= "Clearfix" >
<li class= "Current" ><a href= "#" > Home </a></li>
<li><a href= "#" > Books </a></li>
<li><a href= "#" > Department store </a></li>
<li><a href= "#" > Brand </a></li>
<li><a href= "#" > Promotions </a></li>
</ul>
</div>
</div>
<div id= "Childnav" >
<div class= "Wrap" >
<ul class= "Clearfix" >
<li class= "First" ><a href= "#" > Music </a></li>
<li><a href= "#" > Film </a></li>
<li><a href= "#" > Kids </a></li>
<li><a href= "#" > Anime </a></li>
<li><a href= "#" > Fiction </a></li>
<li><a href= "#" > Foreign Languages </a></li>
<li><a href= "#" > Digital camera </a></li>
<li><a href= "#" > Notebooks </a></li>
<li><a href= "#" > Down jacket </a></li>
<li><a href= "#" > Autumn/Winter Boots </a></li>
<li><a href= "#" > Sneakers </a></li>
<li><a href= "#" > Beauty skincare </a></li>
<li><a href= "#" > Home textile Products </a></li>
<li><a href= "#" > Baby milk </a></li>
<li><a href= "#" > Accessories </a></li>
<li class= "Last" ><a href= "#" >investor relations</a></li>
</ul>
</div>
</div>
<div id= "position" class= "wrap" >
You are here: <a href= "index.html" > Easy buy network </a> &gt; Shopping Cart
</div>
<div class= "Wrap" >
<div id= "Shopping" >
<form action= "address.html" >
<table>
<tr>
<th> Product Name </th>
<th> Commodity price </th>
<th> Purchase Quantity </th>
<th> Operations </th>
</tr>
<? Php
$userid = 1;//and addcart.php, which can normally be obtained from the session
try{
$pdo = new PDO ("Mysql:host=localhost;dbname=lian", "Root", "" ", Array (pdo::attr_errmode=>pdo::
errmode_exception));
$pdo->query ("Set names UTF8");
$sql = "Select P.id,p.title,p.price,c.num from Shop_product p right joins Shop_cart C on P.id=c.productid where c.userid=?" ;
$stmt = $pdo->prepare ($sql);
$stmt->execute (Array ($userid));
$data = $stmt->fetchall (PDO::FETCH_ASSOC);
}catch (Pdoexception $e) {
echo $e->getmessage ();
}
?>
<?php
$total = 0;
foreach ($data as $product):
?>
<tr id= "Product_tr" >
&LT;TD class= "thumb" ><a href= "product-view.html" ><?php echo $ product[' title ']?></a></td>
&LT;TD class= "Price" id= "Price_id_0" >
<span id= "Price" >¥<span id= "Product_price" ><?php echo $product [' Price ']?></span></span >
<input type= "hidden" value= "/>"
</td>
&LT;TD class= "Number" >
<input id= "Number_id_0" type= "text" name= "number" value= "<?php echo $product [' num ']?> ' onblur= ' Changenum ( <?php echo $product [' id ']?>,this.value) '/>
</td>
&LT;TD class= "Delete" ><a href= "Javascript:delpro (<?php echo $product [' id ']?>) ' > Delete </a></td >
</tr>
<?php
$total + = $product [' Price ']* $product [' num '];
Endforeach;
?>
</table>
<div class= "Total" ><span id= "All" > Totals: ¥<span id= "Product_total" ><?php echo $total? ></ Span></span></div>
<div class= "button" ><input type= "Submit" value= "/></div>"
</form>
</div>
<script type= "Text/javascript" >
function Changenum (productid,num) {
Use Ajax to pass parameters to PHP backend to make changes to the number of items in the shopping cart table
var url = "changenum.php";
var data = {"ProductID":p roductid, "num": num};
var success = function (response) {
if (Response.errno = = 0) {
var total = ($ ("#number_id_0"). Val ()) * ($ ("#product_price"). html ());
$ ("#product_total"). HTML (total);
}
}
$.post (url,data,success, "json");
}
function DelPro (ProductID) {
Pass the Product ID to the PHP backend via AJAX to remove the data from the shopping cart table
var total = 0;
var url = "delpro.php";
var data = {"ProductID":p Roductid};
var success = function (response) {
if (Response.errno = = 0) {
$ ("#product_tr"). Remove ();
$ ("#product_total"). HTML (total);
}
}
$.get (url,data,success, "json");
}
</script>
<script type= "Text/javascript" >
document.write ("The shopping Cart item ID recorded in the cookie:" + getcookie ("product") + ", which can be read in the dynamic page");
</script>
</div>
<div id= "Footer" >
Copyright &copy; All rights Reserved. Beijing ICP Certificate No. 1,000,001th
</div>
</body>

PHP Delete page:

<?php
//Receive, processing parameters
$productid = intval ($_get[' ProductID ');
$userid = 1;
//delete data
try{
  $pdo = new PDO ("Mysql:host=localhost;dbname=lian", "Root", "" ", Array (pdo::attr_errmode= >pdo::
  errmode_exception));
  $pdo->query ("Set names UTF8");
  $sql = "Delete from Shop_cart where productid=? and userid=? ";
  $stmt = $pdo->prepare ($sql);
  $stmt->execute (Array ($productid, $userid));
  $rows = $stmt->rowcount ();
}catch (pdoexception $e) {
  echo $e->getmessage ();
}
if ($rows) {
  $response = Array (
    "errno" + 0,
     "errmsg" = > "Success",
     "Data"   = True
 );
} else{
  $response = Array (
    "errno" =-1,
     "errmsg" and "fail",
     "data"   = = False
 );
}
Echo Json_encode ($response);

PHP Add page:

<?php
Receive parameters
$productid = intval ($_post[' ProductID ');
$num = intval ($_post[' num ');
Prepare the data to be added to the shopping cart table
$userid = 1;//actual project, the user log in after the $userid is stored in the session, there is no login registration page, directly defined
try{
$pdo = new PDO ("Mysql:host=localhost;dbname=lian", "Root", "" ", Array (pdo::attr_errmode=>pdo::
errmode_exception));
$pdo->query ("Set names UTF8");
$sql = "Select Price from Shop_product where id=?";
$stmt = $pdo->prepare ($sql);
$stmt->execute (Array ($productid));
$data = $stmt->fetch (PDO::FETCH_ASSOC);
$price = $data [' Price '];
$createtime = time ();
Add (also to determine whether the current user in the shopping cart has been added to the product, if you have joined, just modify the quantity, if not joined, and then a complete data added)
$sql = "SELECT * from Shop_cart where productid=? and userid=? ";
$stmt = $pdo->prepare ($sql);
$stmt->execute (Array ($productid, $userid));
$data = $stmt->fetch (PDO::FETCH_ASSOC);
if ($data) {
$sql = "Update Shop_cart set num=num+? where productid=? and userid=? ";
$params = Array ($num, $productid, $userid);
}else{
$sql = "INSERT into Shop_cart (productid,num,userid,price,createtime) VALUES (?,?,?,?,?)";
$params = Array ($productid, $num, $userid, $price, $createtime);
}
$stmt = $pdo->prepare ($sql);
$stmt->execute ($params);
$rows = $stmt->rowcount ();
}catch (Pdoexception $e) {
echo $e->getmessage ();
}
Returns the result of the final addition
if ($rows) {
$response = Array (
' errno ' = 0,
' ErrMsg ' = ' success ',
' Data ' = True
);
}else{
$response = Array (
' errno ' =-1,
' ErrMsg ' = ' fail ',
' Data ' = False
);
}
echo Json_encode ($response);

PHP Modified Product Quantity page:

<?php
Receive AJAX-passed parameters, prepare parameters.
$productid = intval ($_post[' ProductID ');
$num = intval ($_post[' num ');
$userid = 1;//can be obtained from the session under normal conditions
Updating the CART table data
try{
$pdo = new PDO ("Mysql:host=localhost;dbname=lian", "Root", "" ", Array (pdo::attr_errmode=>pdo::
errmode_exception));
$pdo->query ("Set names UTF8");
$sql = "Update Shop_cart set num=? where productid=? and userid=? ";
$stmt = $pdo->prepare ($sql);
$stmt->execute (Array ($num, $productid, $userid));
$rows = $stmt->rowcount ();
}catch (Pdoexception $e) {
echo $e->getmessage ();
}
if ($rows) {
$response = Array (
"errno" = 0,
"ErrMsg" = "Success",
"Data" = True
);
}else{
$response = Array (
"Errno" =-1,
"ErrMsg" = "fail",
"Data" = False
);
}
echo Json_encode ($response);

Summarized as follows:

1,ajax acts as a staging station for transmitting data to and from the front and back, and the page interacts with the front and back data without needing to refresh.

2, the foreground tag element and so on call JavaScript function, the function uses the Ajax to pass the parameter in the background, under jquery There are three ways $get (), $post (),
$ajax (), $get () and $post () parameters have the same meaning, one refers to the URL, the second parameter refers to the data to be passed, the three-parameter refers to the function of the callback after the request succeeds, the four parameters specify the data
Formats, such as JSON, XML, and so on. $ajax () to put a JSON object, that is, with {} extension, {} A reference to the URL, two parameters to pass the parameter, the three-parameter
Refers to the function of the callback after the request succeeds, the four parameters specify the data format, the five-parameter means the transfer method to use, the default is get, can be changed to post. function of the callback function
It is generally used to verify success if the request succeeds and you can continue to manipulate some nodes to change the page effect.
3,PDO Operating Database
try{
$pdo = new PDO ("Mysql:host=localhost;dbname=lian", "Root", "" ", Array (pdo::attr_errmode=>pdo::
errmode_exception));
$pdo->query ("Set names UTF8");
$sql = "Delete from Shop_cart where productid=? and userid=? ";
$stmt = $pdo->prepare ($sql);
$stmt->execute (Array ($productid, $userid));
$rows = $stmt->rowcount ();
}catch (Pdoexception $e) {
echo $e->getmessage ();
}
Where pdo::attr_errmode=>pdo::errmode_exception is setting the exception handling mode
The three worthy distinctions are as follows:
Pdo::errmode_silent
This is the default mode used. PDO will set simple error codes on the statement and database objects, and can use the Pdo->errorcode () and Pdo->errorinfo () methods to check for errors;
Pdo::errmode_warning
When using this mode, PDO will emit a traditional e_warning message.
Pdo::errmode_exception
PDO throws a Pdoexception exception and sets its properties to reflect the error code and error message.

4,php Background Completion Query Modification Delete Add to the results of the AJAX request to the success or not back to the foreground
if ($rows) {
$response = Array (
"errno" = 0,
"ErrMsg" = "Success",
"Data" = True
);
}else{
$response = Array (
"Errno" =-1,
"ErrMsg" = "fail",
"Data" = False
);
}
echo Json_encode ($response);

The application of Ajax in Shopping cart

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.