1

Please tell me how to use AJAX with CodeIgniter. I wrote the view like this but I am not sure how to send data to model with the controller.

My view is:

<html>
<head> 

<script>
    function insert(fname,lname,age)
    {
        if (window.XMLHttpRequest)
        {// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        }
        else
        {// code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
            }
        }

        xmlhttp.open("GET","ajax_db_php.php?fname=fname&lname=lname&age=age",true);
        xmlhttp.send();
    }
</script>
</head>

<body>

<form> 
    <table>
        <tr><td>First Name : </td><td> <input type="text" fname="fname"/> </td> </tr>  
        <tr><td>Last Name : </td><td> <input type="text" fname="lname"/> </td> </tr>
        <tr><td>City : </td><td> <input type="text" fname="age"/> </td> </tr>

        <input type="button" onclick="insert(fname,lname,age)">
    </table>
</form>

</body>
</html> 

Please help me with writing the controller and model for this case.

1
  • You wouldn't want to do it using GET, thats for sure. use POST instead and look at jQuery.post and jQuery.ajax Commented Apr 14, 2014 at 2:50

1 Answer 1

1

This is the idea:

Better use post for submitting forms using ajax:

xmlhttp.open("POST","user_ajax",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname="+fname+"&lname="+lname+"&city="+city);

Model

class user extends CI_Model{
    function insert(){
        $data = array(
                    "fname" => $this->input->post('fname'),
                    "lname" => $this->input->post('lname'),
                    "city" => $this->input->post('city')
                );
        return $this->db->insert("TABLE_NAME",$data);
    }
}

Controller

class user_ajax extends CI_Controller{
    function index(){
        $this->load->model("user");
        if(isset($_POST['fname'])){
            $ths->user->insert();
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.