2

Good day to all.

Im sorry if I asked this question which stopped me now on my development. I am just a newbie in jquery and json which dont know yet how to manipulate the data. Sorry for this.

As a background, here is my VIEW as I am using a CodeIgniter Framework. This Search button (in yellow) is not the default "Search" of the Boostrap Datatable. Since, as my design, I will search first the last name of the employee then hit the search button. If there are records to be retrieved, then I will add/display it in the datatable.

enter image description here

So here is my code:

VIEW:

<div class="panel-body">
    <div class="col-sm-3 col-md-3 pull-right">
        <form class="navbar-form" role="search">
            <div class="input-group">
                <input type="text" class="form-control" placeholder="Search" name="search_empname" id="search_empname" autocomplete="off">                                  

                <div class="input-group-btn">
                    <button class="btn btn-default" type="button" id="btnsearch">
                    <i class="glyphicon glyphicon-search"></i></button>                                     
                </div>                                  
            </div>
        </form>
    </div>

    <div class="table-responsive">
        <table class="table table-striped table-bordered table-hover" id="employee_access_dataTables">
            <thead>
                <tr>
                    <th width="10%">Employee No.</th>
                    <th width="10%">Username</th>
                    <th width="10%">FirstName</th>
                    <th width="10%">MiddleName</th>
                    <th width="10%">LastName</th>                                       
                    <th width="10%">Prim. Role</th>
                    <th width="10%">Sec. Role</th>
                    <th width="10%">Email</th>
                    <th width="10%">Status</th>
                    <th>Action</th>
                </tr>
            </thead>
            <tbody>                         
            </tbody>
        </table>
    </div>

CONTROLLER

public function search_employee() {
    $search_empname = trim($this -> security -> xss_clean($this -> input -> get('lastname')));
    $data['empresult'] = $this -> msystems_admin -> search_employee($search_empname);
    echo json_encode($data);
}

AJAX

$('#btnsearch').click(function(){
    var gv_lname = $('#search_empname').val();

    if(gv_lname != ''){
        $.ajax({
            type:'GET',
            cache: false,
            datatype: 'json',
            url:'<?php echo site_url('csystems/search_employee');?>',
            data:'lastname='+gv_lname,
            success: function(data){
                console.log(data);  
                //I am not sure what to place here          
            }   
        });
    }               
});

Can you please emligthen me how to derive the output I desired? Thank you so much in advance.

NOTE: I cannot display the output of JSON even I do an ALERT. :(

UPDATE: Here's is the Network Tab of the Developer Tool of Chrome. enter image description here

And when I click the URL search_employee, I got nothing preview. enter image description here

enter image description here

UPDATE 2: If I changed my CONTROLLER something like this where I will not pass it like JSON.

public function search_employee() {
    $search_empname     = trim($this -> security -> xss_clean($this -> input -> get('lastname')));
    $data['empresult']  = $this -> msystems_admin -> search_employee($search_empname);
    //echo json_encode($data);

    foreach ($data['empresult'] as $row){
        $output  = $row -> fname;
        $output .= $row -> mname;
        $output .= $row -> lname;
    }

    echo $output;       

}

And in my AJAX, I remove the JSON as datatype such as this one below,

$('#btnsearch').click(function(){
    var gv_lname = $('#search_empname').val();

    if(gv_lname != ''){
        $.ajax({
            type:'GET',
            cache: false,
            //dataType: 'json',
            url:'<?php echo site_url('csystems/search_employee');?>',
            data:'lastname='+gv_lname,
            success: function(data){
                console.log(data);  
                //I am not sure what to place here                          
            }   
        });
    }               

});

Then I got a response as seen from the console logs. Please see the screenshot. enter image description here

I am not sure what's wrong with JSON... :(

YakovL
  • 5,213
  • 10
  • 46
  • 71
levi palmer
  • 185
  • 4
  • 19

3 Answers3

1

use

dataType: 'json',   instead of datatype: 'json',

T should be capital. Hope it works

Punit Gajjar
  • 4,304
  • 7
  • 28
  • 61
  • Their is no output from the endpoint, so that's not the problem. – Gwendal Feb 05 '16 at 08:20
  • Hi @Gwendal, I updated above. Please see UPDATE 2. As I changed my controller returning only not as JSON but as a string and it works. I got a response in the console log. – levi palmer Feb 05 '16 at 08:24
0

First, thanks to @Gwendal and @Praveen for guiding me to this problem. I found the actual error when using JSON.

Using this code in my controller,

var_dump(json_encode($data));
var_dump( json_last_error());

With this code above, it will return a response in the console log. And the response of it is this one below:

bool(false)
int(5)

Now, looking into the PHP manual found here, this error int(5) is related to:

0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8

So right now, I will be looking at the cause of JSON_ERROR_UTF_8.

Thanks to all of you.

UPDATE with this error JSON_ERROR_UTF_8

The reason for this error why it is occurring is that, the JSON format cannot be created from the array returned by the SQL retrieval. It is because of the Resouce ID which is attached to the object. When you do a print_r command, you cannot see the resouce id. But if you do a var_dump, then you will notice that no.

Here the screenshot of the two method:

Using PRINT_R: No Resource ID is seen.

enter image description here

Using VAR_DUMP: Resouce ID is displayed. enter image description here

So from this two screenshots, I have concluded that the returning SQL records have resource id for each record. So, when I encode it using the JSON_ENCODE function, it fails because of that resource id which can't be interpreted.

To solve this issue, I first transpose the resulting SQL result into an associative array then pass that array into the function JSON_ENCODE. With this method, it will give a JSON response.

So in my MODEL, I adjusted this way:

public function search($q) {        
    $sql = "SELECT statment here";
    $query = $this -> db -> query($sql);        
    if ($query -> num_rows() > 0) {
        $ctr = 0;
        foreach($query->result() as $row) {
            //make an associative array
            $data[$ctr]['fname'] = $row->fname;
            $data[$ctr]['mname'] = $row->mname;
            $data[$ctr]['lname'] = $row->lname;
            
            $ctr++;

            //list all the other fields here
        }
        return $data;
    }
    return false;
}

Then in my CONTROLLER, I can now pass this array to JSON_ENCODE function. So,

public function search_employee() {
    $search_empname = trim($this -> security -> xss_clean($this -> input -> get('lastname')));
    $data = $this -> msystems_admin -> search_employee($search_empname);
    echo json_encode($data)     
}

As a result, when I run the frontend search, there is now a response via the AJAX call. enter image description here

Again, a million thanks to everyone who commented. I got the right direction of debugging this issue. I hope this will help also other newbie like me. Kudos.

Community
  • 1
  • 1
levi palmer
  • 185
  • 4
  • 19
0

Your response header has Content-Type: text/html. Try sending the right json header in your response. Add this line to your php before echo:

header('Content-Type: application/json');

See also : jQuery AJAX Call to PHP Script with JSON Return

Community
  • 1
  • 1
Ahmed Essam
  • 956
  • 7
  • 14