0

I've been trying to decode a Javascript array in PHP for several days now with no luck.

I basically have a PHP while loop that loops through all products in my SQL database and it spits out a checkbox on each row to allow users to select 1 or more product to action via a PHP script.

My HTML & form is:

<div class="error_box"><?php echo $_SESSION['newdata']; ?></div>
<div class="error_box"><?php echo $_SESSION['errordata']; ?></div>
<form>
<input type='submit' value='Bulk update products -->' id='bulk-change-products' onClick='updateProduct()'>
<input type='checkbox' name='products[]' id='serialized' value='$product_no' onclick='serialize()'>
</form>

My Javascript code:

window.serialize = function serialize() {
  var values = [].filter.call(document.getElementsByName('products[]'), function(c) {
    return c.checked;
  }).map(function(c) {
    return c.value;
  });

  console.log(values);
  $('#result').html(values);

}

function updateProduct(values){
    $.ajax({
         url: "https://tech-seo.co.uk/ecommerce/products/bulk_process_products.php",
        method: "POST",
        data: {array:values},
        success: function(res){

        }

    }) 
}

Console log shows the data correctly e.g.

(2) ["1", "2"]
0: "1"
1: "2"
length: 2

My php code after posting with AJAX:

session_start();

 $getArray = json_decode($_POST['data']);

// checking if data exists
if ($getArray != null ){
    $_SESSION['newdata'] = "Success!";
}else{
    // either of the values doesn't exist
   $_SESSION['errordata'] = ">>>>>>  There was an error  <<<<<<<";
}

I always get '>>>>>> There was an error <<<<<<<' when I select the products and click the submit button.

Any help is appreciated.

Thanks. Stan.

4
  • 2
    You have data: {array:values} your array is in the array key not data key, eg you would use $_POST['array'] Commented Nov 21, 2019 at 22:47
  • onClick='updateProduct()' You're not passing the values argument to the function. Commented Nov 21, 2019 at 22:55
  • You're calling json_decode() in PHP, but you never call JSON.stringify() in JavaScript. Where are you expecting the JSON to come from? Commented Nov 21, 2019 at 22:56
  • Ive now used stringify var newvalues = JSON.stringify(values); console.log(newvalues); $('#result').html(newvalues); which now results in ["1","2","3"]. Im not sure I understand regarding the values argument? Commented Nov 21, 2019 at 23:03

1 Answer 1

1

You're not passing the values array when you call updateProduct() from the onclick attribute. It needs to get the values itself.

function updateProduct() {
  var values = $("input[name='products[]']:checked").map((i, el) => el.value).get();
  $.ajax({
    url: "https://tech-seo.co.uk/ecommerce/products/bulk_process_products.php",
    method: "POST",
    data: {
      products: values
    },
    success: function(res) {
    }
  })
}

If you pass the array in the data: option, you don't need to use json_decode() in PHP. jQuery will send the parameters using the URL-encoded format that PHP decodes into an array in the $_POST element.

$getArray = $_POST['products'];
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for this Barmar, I knew I was missing something, I can now echo back the values of the array via the $getArray = $_POST['products']; thanks for that. I have a weird issue where the data isnt returned on the first button click, it always seems to be the 2nd click, any ideas?
@StanHowe you did nothing to prevent the event default action inside your updateProduct function, so your form will submit, because you are clicking on a submit button
Ive added an if statement to ensure there is at least one product selected but after i alert on the page, it loads a new URL with a ? at the end, any ideas ?
Change the input to type="button" so it doesn't submit the form.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.