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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | <?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | $(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(); }); |