Ajax Auto-complete search with Code-igniter - php

Ajax Auto-complete search with Code-igniter from my database. I am trying to search my database and Ajax completes the search from items saved on my database. I believe I am missing a simple trick. Maybe I am writing my controller or maybe everything all wrong... Code below
// View Page
Location path: application/views/template/header
<form class="navbar-form" >
<input type="text" id="mysearch" placeholder="search" onkeyup="doSearch();">
<br />
<script>
// This is the jQuery Ajax call
function doSearch()
{
$.ajax({
type: "GET",
url:"localhost/codeigniter/index.php/ajax/getdata/" + $("#mysearch").val(),
success:function(result){
$("#searchresults").html(result);
}});
}
//class example
</script>
Note: My form or search box is inside my header... So my view page is located in template/header
// Controller Page
Location path: codeigniter/application/controller/ajax.php
class Ajax extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('ajax_model');
//$this->load->helper('url_helper');
}
public function form ()
{
$data['title'] = 'Ajax search';
$this->load->view('template/header');
}
// function ends
public function getdata($param = '')
{
// Get data from db
$data['ajaxdata'] = $this->ajax_model->search($param);
// Pass data to view
$this->load->view('template/header', $data);
}
}
?>
// My Model
Location path: application/model/Ajax_model.php
<?php if (! defined('BASEPATH')) exit('No direct script access');
class Ajax_model extends CI_Model
{
public function __construct()
{
$this->load->database();
}
public function search ($title){
$this->db->select('title');
$this->db->select('text');
$this->db->like('title', $title, 'both');
return $this->db->get('news');
}
}
?>
Please be aware I am new to CodeIgniter. It explains my rather obvious ignorance

$data['ajaxdata'] = $this->ajax_model->search($param);
$data['ajaxdata'] = json_encode($data['ajaxdata']);
echo $data['ajaxdata'];
Ajax method expects data in form of (JSON) string. So you don't need to load header again. Instead, just pass needed data from DB and jQuery will put it in designated place. In this case into element with id of searchresults.

Try changing this
$this->load->view('template/header', $data);
to
$content = $this->load->view('template/header', $data,TRUE);
// load view to a variable.
echo $content;

if i am clear what you need try:
first define ajax request type:
function doSearch()
{
$.ajax({
type: "GET",
dataType:"html",
url:"localhost/codeigniter/index.php/ajax/getdata/" + $("#mysearch").val(),
success:function(result){
$("#searchresults").html(result);
}});
}
Then in controller :
just echo your view:
$auto_complete_html = $this->load->view('template/header', $data,TRUE);
echo $auto_complete_html;
//good practice always die(); after ajax called
die();

Try using POST in AJAX instead of GET:
<script>
// This is the jQuery Ajax call
function doSearch()
{
var search = $("#mysearch").val()
$.ajax({
type: "POST",
url:"localhost/codeigniter/ajax/getdata/",
data:'search=' + search,
success:function(data){
$("#searchresults").html(data);
}});
}
//class example
</script>
Then in your controller Get THE POSTED data from AJAX
public function getdata()
{
$param= $this->input->post('search');
// Get data from db
$result = $this->ajax_model->search($param);
// Pass data to view
echo $result;
}

Related

CodeIgniter ajax link not found

I'm having an issue with getting data from Controller, I have tried all the solutions here but it's the same..
when I click on the button it says 404 not found, if I change the URL to completed URL included the controller class name + function name, it says 403
Here is my view code :
<h2>Quiz</h2>
<script type="text/javascript">
$(document).ready(function(){
var BASE_URL = '<?php echo base_url(); ?>';
$('#show').click(function(e){
console.log(BASE_URL);
$.ajax({
url: BASE_URL + "Quiz/get_item",
dataType:'text',
type:"POST",
success: function(result){
var obj = $.parseJSON(result);
console.log(obj);
}
})
})
});
</script>
<button id="show">Show Cutomers</button>
<div id="customers-list"></div>
<p>Our first multi-page CodeIgniter application! Each page has its own controller and view!</p>
Here is my Controller code :
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Quiz extends CI_Controller {
var $TPL;
public function __construct()
{
parent::__construct();
$this->load->model('Quiz_data');
// Your own constructor code
}
function show_customers()
{
$query = $this->db-> query("SELECT * FROM quiz ORDER BY id;");
$this->TPL['listing'] = $query->result_array();
$this->template->show('quiz', $this->TPL);
}
public function index()
{
$this->template->show('quiz', $this->TPL);
}
public function get_item(){
$data = $this ->Quiz_data->get_data();
echo json_encode($data);
}
}
Here is my Model code :
<?php
class Quiz_data extends CI_Model {
public function get_data()
{
$query = $this->db->get('quiz');
return $query -> result_array();
}
}
What is the output of
console.log(BASE_URL);
Didnt mess with CI for quite a while, but it used to need /index.php/ in the URL. Try:
url: BASE_URL + "/index.php/quiz/get_item",
Although the controller-name needs to start with a capital, it doesnt need to be called that way in the URL.
Make sure url: BASE_URL + "Quiz/get_item" provides the correct URL.
var BASE_URL = '<?php echo base_url(); ?>'; May not provide trailing slash and you won't get correct url.
Try updating your call with following:
url: BASE_URL + "/Quiz/get_item",

How to send/return data/value from CI_Controller to AJAX

As the title, i want to CI_Controller return value/data back to AJAX which give request before.
The_Controller.php
class The_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
function postSomething()
{
$isHungry = true;
if(isHunry){
return true;
}else{
return false;
}
}
}
AJAX
$(document).ready(function()
{
$('#form').on('submit', function (e)
{
e.preventDefault(); // prevent page reload
$.ajax ({
type : 'POST', // hide URL
url : '/index.php/The_Controller/postSomething',
data : $('#form').serialize (),
success : function (data)
{
if(data == true)
{
alert ('He is hungry');
}
else
{
alert ('He is not hungry');
}
}
, error: function(xhr, status, error)
{
alert(status+" "+error);
}
});
e.preventDefault();
return true;
});
});
The Problem :
The AJAX code above always get FALSE for variable data. It's not get return value from postSomething function inside CI_Controller.
The Question :
I want to if(data == true) result alert ('He is hungry');. But cause data not fill by return value of postSomething function inside CI_Controller so it always false. How to get return value/data from CI_Controller to AJAX?
Thank you
you need to change your code a little bit. no need to return data, just echo true or echo false from your controller. Hope you will get your desired result.
You have a typo in the PHP code
if(isHunry){
should be
if($isHungry){
Also, returning data to an AJAX request, you really should be sending the correct content type in the header. Ex.
header('Content-Type: application/json');
And print or echo the data, not return it, as well as json_encode it:
echo json_encode($data);
So your postSomething php function should look something like this:
$isHungry = true;
header('Content-Type: application/json');
echo json_encode($isHungry);

How to pass input parameters to controller actions in php mvc with $.get() or $.post() methods ajax jquery?

How to pass input parameters to controller actions in php mvc with $.get() or $.post() methods ajax jquery?
In my php code how can I send $username parameter to checkUserName action?
Can I send this parameter as option data parameter in $.get() or $.pos() ajax?
//my class. this class is for users
class User extends Controller
{
// construct class
function __construct()
{
parent::__construct();
}
// my action. this actin check username in database
public function checkUserName($username)
{
// enter code here
}
}
with post method
function get_username() {
$.ajax({
url:'controller/method',
type: "post",
data: {
'username': username,
},
success: function(data) {
},
});
}
<?php public function checkUserName()
{
$username = $_POST['username'];
or
$username = $_GET['username'];
}
change the type to GET for get method

Codeigniter Ajax request appeared twice in view and database

I have created a comment library to handle comments all over my website developed by CI
I am adding comments using ajax so i have came up with practice to have the function located in MY_Controller that handle the ajax
public function comment_add()
{
echo $this->comments->add();
}
and in AJAX Jquery code noting that category is one of controller names as any controller will havethe access to comment_add() found in parent controller
$('#myform').submit(function(e) {
e.preventDefault();
dataString=$("#myform").serialize();
$.ajax({
type:"POST",
url: base_url+"snc/category/comment_add",
data: dataString,
success: function(data){
$(data).hide().insertAfter('#inserAfterThis').slideDown('slow');
$('#comment_new').val('');
}
}
);
});
and in my Comments library
public function add()
{
$post_id=$this->get_post_id();
$post_type=$this->get_post_type();
if(!$post_id || !$post_type || !$this->user_id)
return false;
$id=$this->ci->comments_model->comment_add($this->user_id,$post_id,$post_type);
if($id)
{
return $this->_markup($id);
}
else
return false;
}
and comments model
function comment_add($user_id,$post_id,$post_type)
{
$data['comment_user_id']=$user_id;
$data['comment_post_type']=$post_type;
$data['comment_post_id']=$post_id;
$data['comment_text']=$this->input->post('comment_new');
$this->db->insert('comments', $data);
if($this->db->affected_rows()>0)
return $this->db->insert_id();
else
return false;
}
Problem is that Comment is inserted twice and as well in database twice, i have been tracin this for hours even with x-Debugg found that he go through echo $this->comments->add(); twice dunno why he would do that, thanks for your help
maybe it was submited twice. Try to unbind submit when you get ajax
success or just alet("something") so you will know if that problem is
javascript or php based.
Replace your submit function with:
$('#myform').submit(function(e) {
e.preventDefault();
dataString=$("#myform").serialize();
$(this).unbind("submit"); //so you will submit only once
$.ajax({
type:"POST",
url: base_url+"snc/category/comment_add",
data: dataString,
success: function(data){
$(data).hide().insertAfter('#inserAfterThis').slideDown('slow');
$('#comment_new').val('');
}
}
);
});
The missing piece here is "snc/category/comment_add" controller ... are you sure you aren't calling from both that controller & also the MY_Controller?
Can you post the controller code as well?
Found out that I have loaded Jquery file twice, that was my bad, thanks guys

codeigniter and ajax cannot access the post

On my website I am using ajax post request to show content around my site, this is done using this code,
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
var data = "calltype=full&url="+url;
$.ajax({
url:url,
type: "POST",
data: data,
success : function (html) {
$('#left-content-holder').html(html);
}
})
});
as you can see I am passing the url into the `$_POST' and I can access this in the method the javascript calls, this method is called get_content_abstract and looks like this,
public function get_content_abstract() {
$this->load->model('content_model');
if($this->input->post('calltype') == "abstract"){
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['abstract'] = $query;
}
$this->load->view('template/abstract', $data);
}
elseif($this->input->post('calltype') == "full") {
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['full'] = $query;
}
$this->load->view('template/full-content', $data);
}
}
How ever I have no added a new function that will allow the user to save the content to 'bookmarking system', however in my method I cannot access the post using codeigniters $this->input-post('url') (where URL is the one of peices of data passed in the javascript), it says that the post is empty when I var dump it, this is done using this method,
public function love_this() {
die(var_dump($this->post->input('url')));
}
can anyone help as to why the post is empty in this love_this method?
Shouldn't:
public function love_this() {
die(var_dump($this->post->input('url')));
}
Actually be
public function love_this() {
die(var_dump($this->input->post('url')));
}
See:
http://codeigniter.com/user_guide/libraries/input.html

Categories