Possible Duplicate:
How to get JavaScript function data into a PHP variable
i have a javascript variable in order.php view and i want to send that variable to a controller and then to the model to write it in to the database.
ex: var myOrderString = "something" to order.php controller.
how to do this?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With