user2796352 user2796352 - 3 months ago 9
Ajax Question

Sending array to controller/model in CI with AJAX

So basically I have a two item array in javascript that is generated based on which link the user clicks. I am trying to send this array to my controller, and then to the model. The model will look at the array and match one of the items to a certain column/row, and will selectively display data.

I am having issues passing the data from AJAX to my controller.

AJAX code (in a .js file)

$('#youmax-video-list-div').append('<div id="testing1"></div>');

$('#concept').click(function(){
console.log(course);
$.ajax({
url: 'http://localhost:8888/index.php/trial/getValues',
type:'POST',
dataType: 'json',
data:'',
error: function(){
$('#testing1').append('<p>goodbye world</p>');
},
success: function(result) {
var htmlStr = '';
$.each(result, function(a, b){
htmlStr += b.qText + '<br />';
});
$('#testing1').append(htmlStr);
} // End of success function of ajax form
}); // End of ajax call
});


I am assuming I must do something with the data field, but I dont know the syntax for it.

The console log in chrome comes up with this:

Array[2]
0: "PL8G0kdHFfE3WuyevUDvwSYCZw8mp8LBFA"
1: "PL8G0kdHFfE3V62Jp2ju-PelOaNUkH7xR8"

Controller

function getValues(){
$this->load->model('get_db');
$data = $this->get_db->getAll();
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));
return $data;
}


Model

class Get_db extends CI_Model{
function getAll(){
$query=$this->db->query("SELECT * FROM questions");
return $query->result();
//returns from this string in the db, converts it into an array

}
}


As I said before, I am really only concerned with getting the data to my controller and my model.
The name of the array is "course". However, that doesnt appear to be so in the console.log. Is that just something chrome does?

Answer

// chkval be the class for elements for the arrays

AJAX function:

function ajaxSub(goals)
{
    var theArray = new Array();
    var i=0;
    jQuery('.chkval').each(function(){
        if(jQuery(this).prop('checked'))
        {
            theArray[i] = jQuery(this).val();
            i++;
        }
    });
    jQuery.ajax({
         url: '<?php echo site_url('mycontroller/myfunctions');?>',
         type: 'post',
         data: {
             arr: theArray,
             other_id: ''
         },
         datatype: 'json',
         success: function () {
         }
    });
}

in the controller:

$arr = $this->post('arr');

foreach($arr as $ar)
{
    echo $ar; // prints each element of the array.
}