2

I am using CodeIgniter and my js code is in my "view" and I want to pass the value in my controller.

var storage =[];

function something()
{

storage.push('the value');

}

Now I want a better way to pass the storage array into my PHP. Thanks in advance. This code is not working because it is in the separate folder.

$.ajax({
    url: 'yourPHPFile.php',
    type: 'POST',
    data: {data:storage.toString()},
    success: function(result) {
            // handle your success
    },
    error: function() {
      // alert("error");
    }
});
Razia sultana
  • 2,168
  • 3
  • 15
  • 20
CodeSlayer
  • 1,318
  • 1
  • 12
  • 34

3 Answers3

3

Easiest way is to use jQuery.

You can do it by sending data to the server using $.ajax

$.ajax({
    url: 'yourPHPFile.php',
    type: 'POST',
    data: {data:storage.toString()},
    success: function(result) {
            // handle your success
    },
    error: function() {
      // alert("error");
    }
});

On server side, in your PHP code do,

$data = $_POST['data'];
echo $data;

$data will contain the value.

AdityaParab
  • 7,024
  • 3
  • 27
  • 40
3

Use JQuery to post the data

$.ajax({ type: "POST",
             url: "Filename.php",
             data: storage,//no need to call JSON.stringify etc... jQ does this for you
             success: function(resopnse)
             {//check response: it's always good to check server output when developing...
                 }});

And in your PHP file

$array=json_decode($_POST['jsondata']);
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
1

Use JSON to write in javascript...

JSON.stringify(array)

and retrieve using...

$array=json_decode($_POST['jsondata']);
jned29
  • 477
  • 12
  • 50