Blog

Post to a MySQL Database Using a jQuery AJAX Form with CodeIgniter
Posted on July 10, 2015 in AJAX, CodeIgniter, MVC, MySQL, PHP by Matt Jennings

Model Example

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Quote extends CI_Model
{

    public function all()
    {
        return $this->db->query("SELECT * FROM quotes")->result_array();
    }

    public function create($new_quote)
    {
        $query = "INSERT INTO quotes (author, quote) VALUES (?, ?)";

        $values = array($new_quote['author'], $new_quote['quote']);

        return $this->db->query($query, $values);
    }

}

Controller Example

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Quotes extends CI_Controller {

    public function index_json()
    {
        $this->load->model('Quote');
        $data['quotes'] = $this->Quote->all();
        echo json_encode($data);
    }

    public function index_html()
    {
        $this->load->model('Quote');
        $data['quotes'] = $this->Quote->all();
        $this->load->view('partials/quotes', $data);
    }

    public function create()
    {
        $this->load->model('Quote');

        $new_quote = $this->input->post();
        $this->Quote->create($new_quote);
        redirect(base_url());
    }

    public function index()
    {
        $this->load->view('index');
    }
}

jQuery AJAX to Read from and Insert into a MySQL Database

$(function() {
    // Get an HTML string to dump into the
    // #quotes DIV later
    $.get('/quotes/index_html', function(result) {

        $('#quotes').html(result);

    });

    // Submit form, add new quote and author into DB,
    // & add show new DB row without reloading page
    $('#add-quote').on('submit', function() {


        $.post('/quotes/create', $(this).serialize(), function(result) {

        });

    });

    // Prevents double-form submission
    // by removing all event handlers from
    // form#add-quote after the form is submitted
    $('#add-quote').off();

});

View that Shows PHP and HTML for the Form

<h1>Quotsy</h1>

<p>Test Image to Ensure Page Doesn't Reload:<br />
    <img src="https://upload.wikimedia.org/wikipedia/commons/b/ba/Soccerball1.png" alt="soccer ball test image"/>
</p>

<form action="<?php echo base_url() . 'quotes/create'; ?>" method="post" id="add-quote">
    <p>
        <label>Author: </label>
        <input type="text" name="author"/>
    </p>

    <p>
        <label>Quote: </label>
        <input type="text" name="quote"/>
    </p>

    <p>
        <input type="submit" value="Add Quote"/>
    </p>
</form>


<div id="quotes">

</div>

Leave a Reply

To Top ↑