mynameisjohn
mynameisjohn

Reputation: 71

Pass a value from controller JSON to view Ajax in CodeIgniter

The problem is I am getting the dialog box of false but the query is running fine and values are successfully added into the database. It should print true, but it is giving me a false. I checked through Firebug also the value res = 1 is going, but I don't know what is wrong in it.

My View:

$.ajax({
    url: "<?php echo site_url('itemsController/additems'); ?>",
    type: 'POST',
    data: form_data,
    success: function(msg) {
        if(msg.res == 1)
        {
            alert(true);
        }
        else
        {
            alert(false);
        }
    }
});

Controller:

        $result = array();
        $this->load->model('itemsModel');
        $query = $this->itemsModel->addItemstoDB($data);

        if ($query){  //&& any other condition
            $result['res'] = 1;
        }
        else
        {
            $result['res'] = 0;
        }
        echo json_encode($result); //At the end of the function.
    }
}

Upvotes: 1

Views: 3960

Answers (2)

aziz punjani
aziz punjani

Reputation: 25776

Try setting your dataType to json so the data sent back from the server gets parsed as JSON.

$.ajax({
    url: "<?php echo site_url('itemsController/additems'); ?>",
    type: 'POST',
    data: form_data,
    dataType: 'json',
    success: function(msg) {
        if(msg.res == 1) {
            alert(true);
        }
        else
        {
            alert(false);
        }
    }
});

Upvotes: 5

Insyte
Insyte

Reputation: 2236

Notice return.

    if ($query){
        $result['res'] = 1;
    }
    else 
    {
        $result['res'] = 0;
    }
    return json_encode($result);//at the end of the function.
}

Upvotes: -2

Related Questions