1

I've got a little project I'm currently working on and its main idea is to create a good-looking user interface and grant the user the option to make searches on a given database.

I've got a working CodeIgniter framework that runs on php5 and integrates with MySQL server that as for now only stores users and passwords. Moreover, I've got a login interface that grants a home page after a successful login (I know...not much, and clearly not something to be proud of).

In the user homepage, I want to create a good-looking live search interface that will allow a user to execute a custom search query that bases on the following criteria: Location, Keywords, Categories and Times.

From the above information, one can conclude that I am a newbie. And he is correct. I have a very little knowledge in php and I see this project as a great opportunity of learning it.

I don't request the full code. I ask only for some examples, explanations, inspirations, ideas, and places to learn from.

That'll be all!

Thanks a lot!

-------------------------------------------------------------Edit--------------------------------------------------------------

OK. so...I followed this guide: http://www.technicalkeeda.com/jquery/live-search-using-jquery-ajax-php-codeigniter-and-mysql

and nothing worked. I updated a few lines that my eye caught as an old CodeIgniter syntax, and it still did not work.

Here's "my" code:

Controller - Person.php

<?php
class Person extends CI_Controller {

 function __construct(){
  parent::__construct();
  $this->load->model('Person_model');
 }

 public function index(){
  $search = $this->input->post('search');
  $query = $this->Person_model->getPerson($search);
  echo json_encode ($query);
 }
}
?>

Model - Person_model.php

<?php
class Person_model extends CI_Model {

public function getPerson($search){
  $this->load->database();
  $query = $this->db->query("SELECT * FROM People where last_name like '%$search%' ");
  return $query->result();
 }
?>

View - home.php

<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<style>
#search {
 background-color: lightyellow;
 outline: medium none;
 padding: 8px;
 width: 300px;
 border-radius: 2px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
 border-radius: 3px;
 border: 2px solid orange;
}

ul {
 width: 300px;
 margin: 0px;
 padding-left: 0px;
}

ul li {
 list-style: none;
 background-color: lightgray;
 margin: 1px;
 padding: 1px;
 -moz-border-radius: 3px;
 -webkit-border-radius: 3px;
 border-radius: 3px;
}
</style>
<script type="text/javascript" language="javascript" src="http://www.technicalkeeda.com/js/javascripts/plugin/jquery.js"></script>
<script type="text/javascript" src="http://www.technicalkeeda.com/js/javascripts/plugin/json2.js"></script>
<script>
 $(document).ready(function(){
   $("#search").keyup(function(){
  if($("#search").val().length>3){
  $.ajax({
   type: "post",
   url: "http://localhost/index.php/Person",
   cache: false,    
   data:'search='+$("#search").val(),
   success: function(response){
    $('#finalResult').html("");
    var obj = JSON.parse(response);
    if(obj.length>0){
     try{
      var items=[];  
      $.each(obj, function(i,val){           
          items.push($('<li/>').text(val.LAST_NAME + " " + val.ID));
      }); 
      $('#finalResult').append.apply($('#finalResult'), items);
     }catch(e) {  
      alert('Exception while request..');
     }  
    }else{
     $('#finalResult').html($('<li/>').text("No Data Found"));  
    }  

   },
   error: function(){      
    alert('Error while request..');
   }
  });
  }
  return false;
   });
 });
</script>
</head>
<body>
<h1>Welcome <?= $this->session->userdata('username') ?></h1>
<a href="<?= site_url('home/logout') ?>">Logout</a>
<div id="container">
<p>Note:- Search by last name!</p>
<input type="text" name="search" id="search" />
<ul id="finalResult"></ul>
</div>
</body>
</html>

I am being presented with an alert box that says: 'Error while request..'

What do I do?

Feel free to capslock at me and ask me questions that I might not know the answer for.

Will appreciate any help!

Sybrid
  • 63
  • 1
  • 9

3 Answers3

1

Okay problem solved! For those who are going to tackle the frustration that I had in the past 2 days, fear no more! What you got to do is to put the following code in your controller (mine is Person.php):

  $this->output->set_header("Access-Control-Allow-Origin: *");
  $this->output->set_header("Access-Control-Expose-Headers: Access-Control Allow-Origin");
  $this->output->set_status_header(200);
  $this->output->set_content_type('application/json; charset=utf-8');
  $this->output->_display();

This allows to send and receive data from different sites, roughly speaking. You can read more about it here. Afterwards, you got to add dataType: 'json' to the page that is sending the query and gets back a parsed json response (mine is view -> home.php).

Hope this will help!

Community
  • 1
  • 1
Sybrid
  • 63
  • 1
  • 9
0

I am trying my level best for your help ,this code may help you to solve your query

Controller - Person.php

<?php
class Person extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('Person_model');    /* Model is called in controller */
    }

    /**
     * Function disc : function for get value from user input by post method 
     * $this->input->post (Codeigniter ) is equivalent to $_POST (Core PHP)
    */

    public function index() {
        $search = $this->input->post('search');
        $query = $this->Person_model->get_person($search); 
        echo json_encode($query);
    }
}
?>

Model - Person_model.php

<?php
class Person_model extends CI_Model {

    /* Function for get searched data from database */
    public function get_person($search=NULL) {
        $this->db->select('*');
        $this->db->from('People'); /* "People as database table name" */
        $this->db->like('last_name', $search);
        $query = $this->db->get()->result();

        if(!empty($query)) {
            return $query;
        } else {
            return FALSE;
        }
    }
}
?>

View - home.php

<html>
    <head>
    <title>Home</title>
    <style>
        #search {
             background-color: lightyellow;
             outline: medium none;
             padding: 8px;
             width: 300px;
             border-radius: 2px;
             -moz-border-radius: 3px;
             -webkit-border-radius: 3px;
             border-radius: 3px;
             border: 2px solid orange;
        }

        ul {
            width: 300px;
            margin: 0px;
             padding-left: 0px;
        }

        ul li {
            list-style: none;
            background-color: lightgray;
            margin: 1px;
            padding: 1px;
            -moz-border-radius: 3px;
            -webkit-border-radius: 3px;
            border-radius: 3px;
        }
    </style>

    <!--Use jQuery CDN service for JQuery Ajax -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
    <!--End-->
    <script>
        $(document).ready(function(){
            $("#search").keyup(function(){
                if($("#search").val().length>3){
                    $.ajax({
                        type: "post",
                        url: "http://localhost/index.php/Person",
                        cache: false,    
                        data:'search='+$("#search").val(),
                        success: function(response){
                            $('#finalResult').html("");
                            var obj = JSON.parse(response);
                            if(obj.length>0){
                                try{
                                    var items=[];  
                                    $.each(obj, function(i,val){           
                                        items.push($('<li/>').text(val.LAST_NAME + " " + val.ID));
                                    }); 
                                    $('#finalResult').append.apply($('#finalResult'), items);
                                }catch(e) {  
                                    alert('Exception while request..');
                                }  
                            }else{
                                     $('#finalResult').html($('<li/>').text("No Data Found"));  
                                }  
                            },
                            error: function(){      
                                alert('Error while request..');
                            }
                        });
                    }
                    return false;
                });
            });
        </script>
    </head>
    <body>
        <h1>Welcome <?php echo $this->session->userdata('username') ?></h1>
        <a href="<?php echo site_url('home/logout') ?>">Logout</a>
        <div id="container">
            <p>Note:- Search by last name!</p>
            <input type="text" name="search" id="search" />
            <ul id="finalResult"></ul>
        </div>
    </body>
</html>

Check console to Debug ajax related errors

Thilina Sampath
  • 3,615
  • 6
  • 39
  • 65
Aman Kumar
  • 4,533
  • 3
  • 18
  • 40
  • Thank you for your time! I really appreciate your help. This did not work for me though...I really don't know what's the problem. Maybe it can't parse the mysql response correctly? I am still getting the 'Error while request..' alert... And how do I debug ajax related errors? which console? – Sybrid Jun 18 '16 at 19:27
  • ok so I found out how to use the console. this is the error I get: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/index.php/Person. (Reason: CORS header 'Access-Control-Allow-Origin' missing). (unknown) – Sybrid Jun 18 '16 at 19:45
  • I posted an answer. But I still have one problem. Now everything is good, but I get 'No Data Found', no matter what I put in the input text field. What could be the problem? – Sybrid Jun 18 '16 at 20:30
  • You may check your model query by this `$this->db->last_query();` before return the $query or below `$this->db->get()->result(); die('here');` , this return you your mysql query you can check this query to run it in mysql. – Aman Kumar Jun 19 '16 at 14:47
0

Understand your problem. These days live search is very cool and good looking feature for any web application. You can make one for your web application very easily. Don't be panic just follow the steps below.

HTML

<div class="col-md-4 col-md-offset-4 ui-widget"> 
     <label for="tags">Search: </label> 
     <input id="tags">    
</div>

JQuery

 $( function() {    
        $( "#tags" ).autocomplete({      
            source: function(request, response) {
                $.ajax({
                    url: 'ajax_autocomplete_demo',
                    dataType: "json", 
                    data: request, 
                    success: function (data) {
                        if (data.length == 0) {
                            alert('No entries found!');              
                        }else {                
                            response(data);                          
                        }
                      }
                 });      
             },    
         });  
     });

Controller

public function ajax_autocomplete_demo(){
        $searchText = $_GET['term'];
        $availableResults = $this->user_model->get_autocomplete_results($searchText);

        if(!empty($availableResults)){            
            foreach ($availableResults as $key => $value) {                
                $searchData[] = $value['country'];
            }        
        }else{
            $searchData[] = '';
        }

        echo json_encode($searchData); 
     }

Model

public function get_autocomplete_results($search_term) { 
        $this->db->SELECT('country'); 
        $this->db->like('country',$search_term); 
        $query = $this->db->get('country_table'); 
        return $query->result_array(); 
    }

Above code is just the login behind live search. If you want a detail solution then follow this link . It has a very good explanation for this.

Sachin Jaiswal
  • 143
  • 1
  • 9