将ajax的值传给控制器,javascript – 如何通过ajax将隐藏字段值传递给codeigniter控制器…

  • Post author:
  • Post category:java


我有一个包含按钮(链接)的视图文件:


Save

在这个视图的其他地方,我还在一个包含我的userid和vacancyid的表单中声明了一些隐藏字段.

echo form_input(dataHiddenArray(‘userid’, $this->auth_user_id));

echo form_input(dataHiddenArray(‘vacancyid’, $vacancydetails[0]->vacancy_id));

这些隐藏字段转换为:

现在我希望能够将这些值发送到我的控制器(通过AJAX),以便我可以将它们插入到我的数据库中.

我的JS文件如下所示:

$(function() {

var postData = {

“userid” : $(“input.userid”).val(),

“vacancyid” : $(“input.vacancyid”).val()

};

btnSave = $(‘#savebutton’),

ajaxOptions = {

cache: false,

type: ‘POST’,

url: “<?php echo base_url();?>dashboard/vacancy/saveVacancy”,

contentType: ‘application/json’,

dataType: ‘text’

};

btnSave.click(function (ev) {

var options = $.extend({}, ajaxOptions, {

//data : $(this).closest(‘form’).serialize()

data: postData

});

ev.preventDefault();

// ajax done & fail

$.ajax(options).done(function(data) {

alert(data); // plausible [Object object]

//alert(data[0]); // plausible data

console.log(data); // debug as an object

}).fail(function (xhr, status, error) {

console.warn(xhr);

console.warn(status);

console.warn(error);

});

});

我的控制器看起来像这样(它没有做太多,因为它不返回任何东西):

public function saveVacancy() {

//$this->load->model(‘user/usersavedvacancies_model’);

/*$data = array(

‘userid’ => $this->input->post(‘userid’),

‘vacancyid’=>$this->input->post(‘vacancyid’)

);*/

echo $this->input->post(‘userid’);

}

解决方法:

对javascript的微小更改

$(function () {

var postData = {

“userid”: $(“input.userid”).val(),

“vacancyid”: $(“input.vacancyid”).val()

};

btnSave = $(‘#savebutton’),

ajaxOptions = {

type: ‘POST’,

url: “<?php echo base_url(‘dashboard/vacancy/saveVacancy);?>”,

dataType: ‘json’

};

btnSave.click(function (ev) {

var options = $.extend({}, ajaxOptions, {

//data : $(this).closest(‘form’).serialize()

data: postData

});

ev.preventDefault();

// ajax done & fail

$.ajax(options).done(function (data) {

console.log(data); // debug as an object

if (data.result === ‘success’) {

alert(“Yeah, it saved userid ” + data.userid + ” to vacancy id ” + data.vacancyid);

}

}).fail(function (xhr, status, error) {

console.warn(xhr);

console.warn(status);

console.warn(error);

});

});

});

在控制器中

public function saveVacancy()

{

//assigning a more useable object name to the model during load

$this->load->model(‘user/usersavedvacancies_model’, ‘save_vacancy’);

$data = array(

‘userid’ => $this->input->post(‘userid’),

‘vacancyid’ => $this->input->post(‘vacancyid’)

);

//send data to model and model returns true or false for success or failure

$saved = $this->save_vacancy->doSaveId($data); //yes, I made up the method, change it

$result = $saved ? “success” : “failed”;

echo json_encode(array(‘result’ => $result, ‘userid’ => $data[‘userid’], ‘vacancyid’ => $data[‘vacancyid’]));

}

标签:jquery,php,javascript,ajax,codeigniter

来源: https://codeday.me/bug/20190627/1310071.html