I'm new to all this AJAX thing so I thought that good learning will be to build simple TODO list. Below is index.php and corresponding controller. Index gets loaded without errors, but when I submit my task nothing is happening. Only page gets reloaded. Database is still empty.
index.php
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<h1>Todo</h1>
<form id="add" >
<input type="input" name="task" />
<input type="submit" value="Add" /><br />
</form>
<script>
$("form").submit(function() {
var value = $("input:first").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>todo/add/" + $("input:first").val(),
dataType: 'text',
success: function()
{
var newP = $('<p />').text(value);
$(".todos").append(newP).fadeIn(1000);
}
});
return true;
});
</script>
<div class="todos"></div>
<p>Załadowano w <strong>{elapsed_time}</strong></p>
</body>
controller/todo.php
<?php
class Todo extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('todo_model');
}
public function index($type = NULL)
{
$this->load->view('todo/index');
}
public function add($data)
{
$this->Todo_model->add($this->input->xss_clean($data));
}
}
?>
Update: todo_model.php:
<?php
class Todo_model extends CI_Model {
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function add($data)
{
$this->db->insert('todo', $data);
}
public function get()
{
return $this->db->get('todo')->result();
}
}
?>
Try using this:
public function add($data)
{
$this->Todo_model->add($data);
}
instead of:
public function add($data)
{
$this->Todo_model->add($this->input->xss_clean($data));
}
UPDATE:
JAVASCRIPT:
$.ajax({
method: 'POST',
url: '<?php echo base_url(); ?>todo/add/',
data: 'data=' + $("input:first").val(),
success: function(resp) {
//rest processing
}
});
CONTROLLER:
public function add()
{
$this->Todo_model->add($this->input->post('data'));
}
You'll need to use a debugger like Firebug console to see what the reply of the server is to your request.
In your script section
$(function(){}
is missing, which should be wrapped around your jQuery
if (evt.preventDefault()) { evt.preventDefault(); }else{ evt.returnValue = false; }
Try this one then debug with firebug by clicking on firebug icon then clicking on Console to see what you submit and how the response is
var id = 1;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>todo/add/",
data: {id : id},
success: function()
{
var newP = $('<p />').text(value);
$(".todos").append(newP).fadeIn(1000);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.