Dennis Dennis - 2 months ago 52
PHP Question

How to pass hidden field value via ajax to codeigniter controller

I have a view file which contains a button (link):

<a href id="savebutton" class="btn btn-warning">Save</a>


Somewhere else in this view I have also declared some hidden fields in a form that contain my userid and vacancyid.

echo form_input(dataHiddenArray('userid', $this->auth_user_id));
echo form_input(dataHiddenArray('vacancyid', $vacancydetails[0]->vacancy_id));


These hidden fields translate to:

<input type="hidden" value="2" class="userid">
<input type="hidden" value="1" class="vacancyid">


Now I want to be able to send these values to my controller (via AJAX) so that I can insert them in my database.

My JS file looks like this:

$(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);
});
});


And my controller looks like this (it is not doing much because it doesn't return anything):

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');
}

Answer

Minor changes to 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);
        });
    });
});

In the controller

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']));
}
Comments