Sending javascript variable from view to controller in Codeigniter [duplicate] Sending javascript variable from view to controller in Codeigniter [duplicate] codeigniter codeigniter

Sending javascript variable from view to controller in Codeigniter [duplicate]


To build on rayan.gigs and antyrat's answers, below is a fix to rayan.gigs answer and how you would receive that information on the controller side:

rayan.gigs fixed answer (modified to match controller example below):

// your html<script>    var myOrderString = "something";    $.ajax({        type: "POST",        url: <?= site_url('OrderController/receiveJavascriptVar'); ?>        data: {"myOrderString": myOrderString},  // fix: need to append your data to the call        success: function (data) {        }    });</script>

The jQuery AJAX docs explain the different functions and parameters available to the AJAX function and I recommend reading it if you are not familiar with jQuery's AJAX functionality. Even if you don't need a success callback, you may still want to implement error so that you can retry the AJAX call, log the error, or notify the user if appropriate.

antyrat (modified to fit controller example below):

<form action="<?= site_url('OrderController/receiveJavascriptVar'); ?>" method="POST"  id="myForm">  <input type="hidden" name="myOrderString" id="myOrderString"></form><script>  var myOrderString = "something";  document.getElementById('myOrderString').value = myOrderString;  document.getElementById('myForm');</script>

The controller could look like this for both of the above cases:

<?php    class OrderController extends CI_Controller    {        public function receiveJavascriptVar()        {            $myJSVar = $this->input->post('myOrderString');            // push to model        }    }?>

I would recommend rayan.gigs method instead of abusing forms. However, if you are trying to submit user information or submit information along side an existing form submission, you could use antyrat's method and just insert a hidden that you fill either on render, or via javascript.


You want to send var from view to anther controller ..... it's mean new request

It's easy to do using Ajax request

In View

 // your html <script>  var X = "bla bla ";   $.ajax     ({     type: "POST",     url: // ur controller,     success: function (html)                            {     }     }); </script>


You can create simple html <form> with hidden field. Assign your JS variable to that field and submit the form.

Simple example:

<form action="order.php" id="myForm">  <input type="hidden" name="myOrderString" id="myOrderString"></form><script>  var myOrderString = "something";  document.getElementById('myOrderString').value = myOrderString;  document.getElementById('myForm');</script>

Now in order.php You will have _GET value of myOrderString.

Also you can do it simply using AJAX.