PHP User
PHP User

Reputation: 2422

codeigniter: send a multidimensional array from view to controller via ajax

I have a php multidimensional array:

$array[0] = array('Jack','[email protected]');
$array[1] = array('one'=>'test1','two'=>'test2'); //unknown data limit 
it could be 5 or 10 or 100 items consider the second array as purchased products.

I want to send this array $array to the controller from the view. I tried:

$newArray = json_encode($array);
$.post('<?=base_url()?>controller/function/<?=$newArray ?>').done(function (res) {
        alert(res);
    });

But I get a security error can't send '[' or '{' in a url. and when I just echo $array in the post it won't work becuase the result will be: "Array".

So the question now is how to send this multidimensional array from view to controller in codeigniter?

Upvotes: 0

Views: 702

Answers (3)

Vali S
Vali S

Reputation: 1461

Use urlencode() (or encodeURIComponent() in javascript) in the view:

$newArray = urlencode(json_encode($array));

OR:

$.post('<?=base_url()?>controller/function/'+encodeURIComponent('<?=$newArray ?>')).done(function (res) {
        alert(res);
    });

and

$json = urldecode($urlencodedjson);

on the receiver side.

Upvotes: 1

BIBIN JOHN
BIBIN JOHN

Reputation: 354

add this code in your view

<script>
   var myJsonString = JSON.stringify(yourArray);
   var url="<?php echo base_url(); ?>/controller/show_json";
   $.ajax({
     type: "POST",
     url: url,
     dataType: 'json',
     data: myJsonString,
     success: function(data){
             console.log(data); 
          }
      });
</script>

add this function on your controllers

function show_json()
{
   print_r($_POST);
}

Upvotes: 1

PHP User
PHP User

Reputation: 2422

In the view:

$newArray = json_encode($array)
$.post('<?=base_url()?>/controller/function',{t:<?=$newArray?>}).done(function (res) {
     alert(res);
});

In the controller:

$arr1 = $_POST['t'][0];
$arr1 = $_POST['t'][1];

Upvotes: 0

Related Questions