0

I wrote a script in post.php for deleting table rows in shopping-cart. I'm sending data with jquery post to a php file. Here is my php file. I created array for outputs and i convert to json with json_encode function.

//Sepetteki Ürünleri Siliyoruz
if(isset($_POST['deleteditems']) && isset($_SESSION['userid'])) {
    $deleted_items = $_POST['deleteditems'];
   //echo $_POST['deleteditems'];
    $sql = "DELETE FROM basket WHERE productid IN ($deleted_items) AND userid = ".$_SESSION['userid'];
    //echo $sql;
    $query = mysql_query($sql);
    $basket_array['queryresult'] = ($query) ? "<i class=\"icon-ok\"></i> Silindi" : "<i class=\"icon-remove\"></i> Hata: Silinemedi";

    $basket_sql = "SELECT p.productid, p.wholesaleprice, p.minquantity, p.vat, b.quantity
                   FROM basket AS b, product AS p
                   WHERE b.productid = p.productid AND b.userid = ".$_SESSION['userid'];
    $basket_query = mysql_query($basket_sql);
    $num   = mysql_num_rows($basket_query);
    if ($num > 0) {
        while ($row = mysql_fetch_array($basket_query)) {
            $wholesaleprice = round($row['wholesaleprice']/(1+$row['vat']/100),2);
            $total_quantity = $row['quantity']*$row['minquantity'];
            $sumnovat[] = $total_quantity * $wholesaleprice;
            $vats[] = array($row['vat'], round(($row['vat']/100)* $total_quantity * $wholesaleprice,2)); // KDV'yi hesaplıyoruz
         }

     foreach ($vats as $vat) {
        $group_by_ratio_vat_sum[] = $vat[0];
     }
        $group_by_ratio_vat_sum = array_unique($group_by_ratio_vat_sum);
        $group_by_ratio_vat_sum = array_fill_keys($group_by_ratio_vat_sum,0);

     foreach ( $vats as $vat ) {
         $number = str_replace( ",", ".", $vat[1] );
         $group_by_ratio_vat_sum[ $vat[0] ] += (float)$number;
     }
        $total_vat = 0;

       $basket_array['tfoot'] = '<tr class="basket_totals"><td colspan="5" class="basketresulttitle">'._('Ara Toplam').'</td><td colspan="3">'.number_format($sumnovat = array_sum($sumnovat),2).' TL</td></tr>';

            foreach ($group_by_ratio_vat_sum as $vat_ratio => $vat_total) {
                $basket_array['tfoot'] .= "<tr class=\"basket_totals\"><td colspan=\"5\" class=\"basketresulttitle\">"._('KDV')." (%$vat_ratio)</td><td colspan=\"3\">".number_format($vat_total,2)." TL</td></tr>";
                $total_vat += $vat_total;
            }

        $basket_array['tfoot'] .= '<tr class="basket_totals"><td colspan="5" class="basketresulttitle">'._('Genel Toplam').'</td><td colspan="3">'.number_format($sumnovat + $total_vat,2).' TL</td></tr>';

        json_encode($basket_array);
    }
}

And here is my jquery code. I want to use json object in my jquery script. But i couldn't do that. Because i'm rookie for json-jquery-php relation. Can you help me ?

$('#basket_delete_button').live('click',function(){
     var loading = '<img src="<?php echo URL; ?>images/style/loading.gif" width="16" height="16">';
     $('.loading').html(loading);
     var deleteditems = $('tbody tr input:checkbox[name="delete_basket[]"]:checked')
                                    .map(function() { return $(this).val() })
                                    .get()
                                    .join(",");

     $.post('post.php',{deleteditems: deleteditems},function(data){
          var obj = JSON.parse(data);
          $('tfoot').html(obj.tfoot);
          $("tbody tr :checked").each(function() {
               $(this).parent().parent().remove()
          });

         var rowCount = $('.basket_products_row').length;
         if (rowCount == 0){
              $('#basket_area').html("<?php echo $basket_error; ?>");
              $('#basket_count').text('0');
         } else {
              $('.loading').html(obj.queryresult);
         }
            });                               
      });

I can't handle jquery json php relation. Can you help me ? I couldn't manage it.

1
  • 1
    It may not help answer your question, but you should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this SO article. Commented Aug 9, 2012 at 13:24

2 Answers 2

2

Try this:

On the server-side (PHP), put a json content type header before any output is send:

header('Content-type: application/json');

and write the output:

echo json_encode(...);

On the client-side (JS), force the $.post to read JSON data:

$.post('someurl.php', 
  {foo:'bar'},
  function(data){},
  'json'  // <--- here
);

You don't need to use JSON.parse() here, jQuery does that for you. You can use data as an object.

After doing the $.post() request, make a console.log(data) to debug the output. And use the browser's debug tools to watch the ajax request output.

Sign up to request clarification or add additional context in comments.

Comments

2

The main issue I see right off the top is that you are encoding your data in PHP, but you are not storing or transmitting that encoded data:

json_encode($basket_array);

That call encodes and returns, but you don't do anything with the return. Try:

echo json_encode($basket_array);

and see what that does for you.

Your client side code could certainly be better (as described in other answers which mention the 4th param to $.post()) but I think your current method of JSON handling in the client will work once you start outputting the data.

1 Comment

i wrote echo here is output {"queryresult":"<\/i> Silindi","tfoot":" Ara Toplam<\/td> 702.04 TL<\/td><\/tr> KDV (%18)<\/td> 126.36 TL<\/td><\/tr> Genel Toplam<\/td> 828.40 TL<\/td><\/tr>"}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.