0

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?

3
  • 1
    As a second argument of $.post Commented Oct 30, 2016 at 15:50
  • Works fine thanks. I'm still not familiar with codeigniter and tried this way without json_encode but didn't work. You can add it as an answer $.post('<?=base_url()?>/controller/function',{t:<?=newArray?>}) Commented Oct 30, 2016 at 16:46
  • You can answer your own question) Commented Oct 30, 2016 at 16:50

3 Answers 3

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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];

Comments

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.