1

I am trying to send an array from js to php through an ajax call.To achieve this i first converted my string to json by using JSON.stringify() and then at the other end i used json_decode() to decode, but it didn't work out.

Using json_last_error() i found the error to be 4.

Js code looks like this

        var form_data = $(this).serialize();

        form_data+='&extraITEMS='+JSON.stringify(extraITEMS);
        var button_content = $(this).find('button[type=submit]');

        form_data=form_data+'&landType='+landType;
        button_content.html('Adding...'); //Loading button text
        $.ajax({ //make ajax request to cart_process.php
            url: "/cart/cart_process.php",
            type: "POST",
            dataType: "json", //expect json value from server
            data: form_data
        }).done(function (data) { //on Ajax success
            $("#cart-info").html(data.items); //total items in cart-info element
            button_content.html('Add to Cart'); //reset button text to original text
            if ($(".shopping-cart-box").css("display") == "block") { //if cart box is still visible
                $(".cart-box").trigger("click"); //trigger click to update the cart box.
            }
        })

I appended my array to the form data.

at the php side

     foreach($_POST as $key => $value){
        $new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING); //create a new product array
    }

    //we need to get product name and price from database.


    if(isset($new_product['extraITEMS']))
    {
    $newPrice=0;
    $extraITEMS=json_decode($new_product['extraITEMS'],true);
    var_export($extraITEMS);
    error_log(stripslashes($new_product['extraITEMS']));
    if(is_array($extraITEMS))
    {
        foreach($extraITEMS as $key=>$value)
        {
            if($value=='cherry'||$value=='chocolate chip'||$value=='butterscotch chip'||$value=='gems')
                $newPrice+=50;
            else if($value=='vanilla'||$value=='pineapple'||$value=='chocolate'||$value=='dark chocolate'||$value=='strawberry'||$value=='blackcurrant'||$value=='grape'||$value=='mango'||$value=='butterscotch')
                $newPrice+=100;
        }

    }
    unset($new_product['extraITEMS']);
   }

enter image description here

This is the snap of firebug console.

How do i correct this problem?

Update:

var_export()

'"[\\"vanilla\\",\\"chocolate\\"]"'

The above console log shows before using JSON.stringify()

Second one show after using it on the array.

enter image description here

Tilak Raj
  • 1,369
  • 5
  • 31
  • 64

1 Answers1

0

I finally found the solution, it was not working due to this code

 foreach($_POST as $key => $value){
        $new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING); //create a new product array
    }

Because json decode doesn't work properly on filter sanitized strings.

Tilak Raj
  • 1,369
  • 5
  • 31
  • 64