我无法将变量传递给我的控制器function.please help
<input type="button" id="mydate" name="mydate" value="<?php echo $dat;?>" class="monthYearPicker" />
script:
$('#mydate').on('click', function () {
var textBoxVal = $(this).val();
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>Money_c/selectallbudget', // link to CI function
data: {
val: $(this).val()
},
success: function (msg) {
console.log(msg);
}
});
});
我如何在我的控制器函数中使用这个javascript变量var textBoxVal = $(this).val()。
controller:
public function selectallbudget(){
$mydate= $this->input->post('val');
$sendMe = $this->money_m->selectbudget($mydate);
echo json_encode($sendMe);
}
答案 0 :(得分:2)
在ajax的帮助下你可以做到。
FIRST: -------------------------------- <!--write this code in you header--> <input type="hidden" value="<?php echo base_url(); ?>" id="baseurl"/>
<!--your javascript code-->
<script type="text/javascript">
var base_url = $('#baseurl').val();
var dateValue = $('#mydate').val();
$.ajax({
url: base_url + "controller_name/function_name", // define here controller then function name
method: 'POST',
data: { date: dateValue }, // pass here your date variable into controller
success:function(result) {
alert(result); // alert your date variable value here
}
});
</script>
<!--your controller function-->
public function budget()
{
$dat = $_POST['date'];
echo $dat;
}
--------------------------------
SECOND: if you want to load any html code then you use this method otherwise above first method
--------------------------------
<!--write this code in you header-->
<input type="hidden" value="<?php echo base_url(); ?>" id="baseurl"/>
<!--your javascript code-->
<script type="text/javascript">
var base_url = $('#baseurl').val();
var dateValue = $('#mydate').val();
$( "#mydate" ).load(
base_url + "controller_name/function_name", // define here controller then function name
{ date: dateValue }, // pass here your date variable into controller
function(){
// write code on success of load function
}
);
</script>
<!--your controller function-->
public function budget()
{
$dat = $_POST['date'];
echo $dat;
}
答案 1 :(得分:2)
您的代码几乎没问题。您的控制器代码只有一处变化:
控制器:
public function selectallbudget(){
//$mydate= $_POST['val']; This is not PHP this is codeigniter
$mydate = $this->input->post('val');
$sendMe = $this->money_m->selectbudget($mydate);
echo json_encode($sendMe);
}
答案 2 :(得分:1)
请使用ajax。这个问题已在这里讨论过了。请参考。
答案 3 :(得分:0)
你在这里做错了$(this).val()
来传递输入值。
this
对象的范围不断变化,当您尝试访问
data: {
val: $(this).val()
}
它试图访问手头的当前对象。
解决方案非常简单(因为您已经将textBoxVal
初始化为输入值。
$('#mydate').on('click', function () {
var textBoxVal = $(this).val();
$.ajax({
type: 'POST',
url: '<?php echo base_url();?>Money_c/selectallbudget', // link to CI function
data: {
val: textBoxVal
},
success: function (msg) {
console.log(msg);
}
});
});