user1329212
user1329212

Reputation:

PHP json_encode data to Jquery

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.

Upvotes: 0

Views: 901

Answers (2)

JAAulde
JAAulde

Reputation: 19550

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.

Upvotes: 2

Pedro L.
Pedro L.

Reputation: 7536

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.

Upvotes: 2

Related Questions