Bobbis
Bobbis

Reputation: 137

How to call controller function from javascript

Creating a web app using mvc and codeigniter. In the view, on the click of a button it calls a javascript method. This method should take the source of 3 images as parameters, and pass them to a controller method. The controller method then turns them into a single $record and passes it to a function in the model, which will then insert the record contents into a database.

View button:

<input type="submit" class="btn btn-primary" value="Assemble bot" onclick="insertAssembled()"></input>

Javascript function:

function assemble(var head, var body, var legs) {
    var head = document.getElementById("HeadImage".src);
    var body = document.getElementById("BodyImage".src);
    var legs = document.getElementById("FeetImage".src);
    // call controller function here, passing head body and legs
}

Controller method:

    public function insertAssembled($head, $body, $legs) {
        //Build record and send to saveBot       
        $record['id'] = 1;
        $record['head'] = $head;
        $record['body'] = $body;
        $record['legs'] = $legs;
        $this->Robotsdata->saveBot($record);
   }

Model method (very rough, help not needed just trying to pass parameters):

public function saveBot($record) {
    $con = mysql_connect("localhost","root@localhost","");
    mysql_select_db("factory", $con);
    $bot_id = $_POST['id'];
    $bot_head = $_POST['head'];
    $bot_body = $_POST['body'];
    $bot_legs = $_POST['legs'];
    $query = "INSERT INTO `factory`.`assembledbots` ('id', 'head', 'body', 'legs') "
            . "VALUES ('$bot_id', '$bot_head', '$bot_body', '$bot_legs');";
    mysql_query($query);
    mysql_close($con);
}

Upvotes: 2

Views: 7907

Answers (2)

Keith Asilom
Keith Asilom

Reputation: 179

You can achieve this by using ajax. Also, in your model, try using CI's Query Builder Class (Active Record) so your queries are safe and to avoid SQL injections.

javascript

function assemble(var head, var body, var legs) {
   var head = document.getElementById("HeadImage".src);
   var body = document.getElementById("BodyImage".src);
   var legs = document.getElementById("FeetImage".src);

   //ajax
   //you post variables
   var fields = {
      head  : head,
      body  : body,
      legs  : legs,
      submit_a: true
   };

   $.ajax({
     url: 'domain/controller/insertAssembled',
     type: 'POST',
     data: fields,
     dataType:'JSON',
     success: function(result){
        console.log(result);
     }
   });
}

controller

public function insertAssembled() 
{

  if ($this->input->is_ajax_request()) { // just additional, to make sure request is from ajax
    if ($this->input->post('submit_a')) {
        $record['id'] = 1;
        $record['head'] = $this->input->post('head');
        $record['body'] = $this->input->post('body');
        $record['legs'] = $this->input->post('legs');

        // to model
        $this->Robotsdata->saveBot($record);

        // return to view
        echo json_encode(array("error"=>false));
        return false;
    }
  }
}

model

public function saveBot($record) 
{
  if ($record) {

    $save_fields = array(
        'id'   => $record['id'],
        'head' => $record['head'],
        'body' => $record['body'],
        'legs' => $record['legs']
    );
    $this->db->insert('table_name', $save_fields);

    return true;
  }
  return false;
}

Upvotes: 1

RomainP.
RomainP.

Reputation: 21

You can try to pass your datas using ajax if you've included the jQuery library :

$.ajax({
    url: 'Path/To/YourController.php',
    type: 'POST',
    dataType: 'text',
    data: {
        head: head, //You'll get it with $_POST['head']
        body: body, //You'll get it with $_POST['body']
        legs: legs  //You'll get it with $_POST['legs']
    },
})
.done(function(data) {
    // Do what you want in case of success
})
.fail(function(err) {
    //Do what you want incase of error
});

Upvotes: 1

Related Questions