javascript - How to return two html contents from ajax? -


i'm developing shopping cart application in php, have 2 functions, first function display total items in cart , second function list products in cart.

how can return 2 function's html output ajax?

here php server side:

<?php require '../init.php'; require $root . '/functions/basic.php'; require $root . '/functions/products.php';  if(isset($_request['id'])) {      $product_id = $_request['id'];      $_session['cart'][$product_id] = isset($_session['cart'][$product_id]) ? $_session['cart'][$product_id] : "";     if($product_id && !productexists($product_id)) {         die("error. product doesn't exist");     }      $qty = dbrow("select id, quantity products id = $product_id");     $quantity = $qty['quantity'];     if($_session['cart'][$product_id] < $quantity)     {         $_session['cart'][$product_id] += 1; //add 1 quantity of product id $product_id      }  }  function writecarttotal() {     echo '     <div class="col-md-4">         <a href="carts"><h1><span class="glyphicon glyphicon-shopping-cart"></span>      ';                         if(isset($_session['cart']))                 {                     $cart_count=count($_session['cart']);                     echo $cart_count;                 }                 else{                     echo "0";                 }     echo '          items         </h1></a>     </div>     <div class="col-md-4">         <h1>     ';             if(!empty($_session['cart'])) { //if cart isn't empty                 $total = "";                 $total_score = "";                 //iterate through cart, $product_id key , $quantity value                 foreach($_session['cart'] $product_id => $quantity) {                       //get name, description , price database - depend on database implementation.                     //use sprintf make sure $product_id inserted query number - prevent sql injection                     $sql = dbquery("select product_title, product_description, price, product_score products id = " . $product_id);                      $count = $sql->rowcount();                      //only display row if there product (though there should have checked)                     if($count > 0) {                          list($name, $description, $price, $score) = $sql->fetch(pdo::fetch_num);                          $line_cost = $price * $quantity; //work out line cost                         $line_score = $score * $quantity;                         $total = $total + $line_cost; //add total cost                         $total_score = $total_score + $line_score;                     }                  }                 //show total                  echo '<span class="label label-success">'. number_format($total) . " <span> ₭</span></span>";     echo '               </h1>     </div>     <div class="col-md-4">         <h1>     ';                    echo '<span class="label label-success">'. number_format($total_score) . " <span > pg</span></span>";                }else{             //otherwise tell user have no items in cart                 echo "0";              }     echo '         </h1>     </div>     '; }  function writecartsummary() {     echo '<h1>welcome cart</h1>';     if(!empty($_session['cart'])) { //if cart isn't empty         $total = "";         $total_score = "";     //show cart          echo "<table class=\"table table-hovered table-bordered\" border=\"1\" padding=\"3\" width=\"40%\">"; //format cart using html table         echo '<tr>                 <th align="center">product name</th>                 <th align="center">quantity</th>                 <th align="center">price</th>                 <th align="center">score</th>                 <th align="center">delete</th>                 </tr>';           //iterate through cart, $product_id key , $quantity value         foreach($_session['cart'] $product_id => $quantity) {               //get name, description , price database - depend on database implementation.             //use sprintf make sure $product_id inserted query number - prevent sql injection             $sql = dbquery("select product_title, product_description, price, product_score products id = " . $product_id);              $count = $sql->rowcount();              //only display row if there product (though there should have checked)             if($count > 0) {                  list($name, $description, $price, $score) = $sql->fetch(pdo::fetch_num);                  $line_cost = $price * $quantity; //work out line cost                 $line_score = $score * $quantity;                 $total = $total + $line_cost; //add total cost                 $total_score = $total_score + $line_score;                  echo "<tr>";                 //show information in table cells                 echo "<td align=\"center\">$name</td>";                 //along 'remove' link next quantity - links page, action of remove, , id of current product                 echo "<td align=\"center\">$quantity</td>";                 echo "<td align=\"center\"><h4>". number_format($line_cost) . " <span class='label label-success'> ₭</span></h4></td>";                 echo "<td align=\"center\"><h4>". number_format($line_score) . " <span class='label label-success'> pg</span></h4></td>";                 echo '<td><a href="?action=delete&amp;id='.$product_id.'" class="btn btn-danger btn-sm">delete</a>';                 echo "</tr>";              }          }          //show total         echo "<tr>";         echo "<td colspan=\"2\" align=\"right\"><h1>total</h1></td>";         echo "<td align=\"right\"><h1>". number_format($total) . " <span class='label label-success'> ₭</span></h1></td>";         echo "<td align=\"right\"><h1>". number_format($total_score) . " <span class='label label-success'> pg</span></h1></td>";         echo "</tr>";          //show empty cart link - links page, action of empty. simple bit of javascript in onlick event of link asks user confirmation         echo "</table>";        }else{     //otherwise tell user have no items in cart         echo "<div class='well'><h3>you have no items in shopping cart.</h3></div>";      } } $value = array("response"=>"ok","totals"=>writecarttotal(), "summaries"=>writecartsummary());  echo json_encode($value); ?> 

and ajax call method:

function isnumber(n) {     return !isnan(parsefloat(n)) && isfinite(n); } $(document).ready(function(){    $("a.add_to_cart").click(function(){     var id = $(this).attr('id');     var productname = $(".product_name_page").attr('id');      if(isnumber(id))     {         //alert("ok");         $.ajax({             type: "get",             url: "ajax/ajaxaddtocart.php",             data: "id=" + id,             datatype: "html",             cache: false,             success: function(data){                 if(data.response == "ok")                 {                     swal("success!", productname, "success");                     $("#load_item_total").html(data.totals);                     $("#navbar_shopping_cart").html(data.summaries);                  }                 else                 {                     $.alert({                         title: '<h3 style="color: red;">error!</h3>',                         content: "<span class=''>there error, please try again!</span>",                         confirm: function(){                          }                     });                 }             }         });     }  }); }); 

my question how return 2 html contents function ajax?

i used json_encode() return no luck

please help...!

you echoing html out instead of storing in string. fix this, fastest way redirect echo outputs php variable:

ob_start(); writecartsummary(); $cartsummary = ob_get_clean();  ob_start(); writecarttotal(); $carttotal = ob_get_clean();  $value = array("response"=>"ok","totals"=>$carttotal , "summaries"=>$cartsummary );  echo json_encode($value); 

with ob_start , ob_get_clean redirect echo standard outputbuffer variable. , can put variable content json data.

further, json-data response, need use datatype: 'json' in ajax call:

 $.ajax({    /* ... */    datatype: "json",    /* ... */  }); 

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -