I added
<script type="text/javasript" src="<?=base_url()?>js/jquery-1.7.2.min.js"></script>
in application/views/templatess/header.php and to post data to Controller using jQuery I wrote
<script>
$(document).ready(function(){
$('#submit').click(function() {
$.ajax({
type : 'POST',
url : '/projects/create',
data: {
pro_name : $('#pro_name').val()
},
success:function (data) {
$("#log_msg").html(data);
}
});
});
});
</script>
in my view file: application/views/project/create.php and the controller exists in application/controllers/projects.php
In my view named create.php the complete code is:
<label for="pro_name">Project Name</label>
<input type="input" id="pro_name" name="pro_name" />
<br />
<input type="submit" id="submit" name="submit" value="Create" />
<script>
$(document).ready(function(){
$('#submit').click(function() {
$.ajax({
type : 'POST',
url : '/projects/create',
data: {
email : $('#pro_name').val()
},
success:function (data) {
$("#log_msg").html(data);
}
});
});
});
</script>
and my controller named projects contains
class Projects extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('projects_model');
$this->load->helper('url');
$this->load->helper('html');
$this->load->helper('form');
$this->load->library('form_validation');
}
public function create()
{
echo $this->input->post('pro_name');
$data['title'] = 'SPARCS | Create Project';
$this->form_validation->set_rules('pro_name', 'Name', 'required');
$this->form_validation->set_rules('pro_client', 'Client', 'required');
$this->form_validation->set_rules('pro_loc_city', 'City', 'required');
$this->form_validation->set_rules('pro_loc_state', 'State', 'required');
$this->form_validation->set_rules('pro_size', 'Project Size', 'required');
$this->form_validation->set_rules('pro_desc', 'Description', 'required');
if ($this->form_validation->run() === FALSE)
{
$this->load->view('templates/header', $data);
$this->load->view('projects/create');
$this->load->view('templates/footer');
}
else
{
// If project name already exists?
$query = $this->projects_model->if_exists($this->input->post('pro_name'));
if ( sizeof($query) == 0) {
//$this->projects_model->set_project();
$data['message'] = 'Add successfully';
} else {
$data['message'] = 'Project name already exists';
}
$this->load->view('projects/log_message', $data);
}
}
}
But browser says $ is not defined
Now please let me know how to setup jQuery in CodeIgniter and what is the correct way to pass data to the controller and also show response send back from the controller
Is it possible that somewhere in your code, jQuery is being set into “safe mode“?
Try wrapping your logic in an anonymous function, like this:
Whatever is in this function is guaranteed to work with
$as a shortcut forjQuery.