Batch Ajax Database Update In Codeigniter

There’s no shortage of solutions to this common question, but I had trouble with many of them. Here's the one that worked for me.

codeigniter,php,mysql,ajax

There's no shortage of blog posts and stack overflow answers on this, but in trying to accomplish this very common task, I came across a lot of supposed solutions to this, so I thought I'd post the one that worked for me.

Take an array of data:



var updateArray = [
  { id: 1, name: 'name1' },
  {id: 2, name: 'name2'
];

You want to find the rows in your mySQL database that have this id, and update their name. First you need to conduct the ajax post:


$.ajax({
   type: "POST",
   url: 'names/update',
   data: {'data' : updateArray },
   failure: function(errMsg) {
    console.error("error:",errMsg);
   },
   success:function(data){
    //do something
   }
});

note that for the "data" parameter of our ajax post, we are putting our array into an object with the key "data". That key can be called whatever you like, but in order for codeigniter to understand it, we need to put it into an object with a key.

Now in your "names" controller within codeigniter, you need to receive the data from ajax:


public function update(){
  $result = $this->name_model->update_names();
}

So the variable $result will be whatever your name_model returns back to the controller. Then in your model, you need to update the database:


public function update_names(){
    $data = $this->input->post('data');
    $this->db->update_batch('db_names', $data, 'id');
}

Here we're assigning a variable called data to the array posted from jQuery with AJAX. Then we're calling Code Igniter's update_batch function, which will save us from having to loop through each item in the array and conduct a separate post. Update batch has three parameters - the table name, the data we are updating, and the key we want to use in the 'where' clause.

That's all there is to it. Return whatever you like back to your controller, and echo that back to your javascript and it will be accessible as the variable "data" in your success function.