0

Hi all I have a site developed in codeigniter. In some function I have to retrieve data from mysql and print the result in javascript because is an ajax call.

Thi is my php function to retrieve data:

public function getCityByNameOnly($name) {
      $query = $this->db->query('SELECT *  FROM city WHERE name LIKE "%'.$name.'%" ');
      $city = array();
      foreach ($query->result() as $row)
     array_push($city, $row);
     return json_encode($city);
      }
}

And this is my ajax call:

$('#ricerca-ajax').keyup(function(){
        var val = $(this).val();
        if (val.length>2){
            var site_url_city ="<?php echo(site_url('/city/get_city_by_text')); ?>";
            $.ajax({   
                url: site_url_city, 
                type: "POST", 
                data: {search: val},
                dataType: "text",             
                success: function(data) {
                    console.log(data);
                    for(var i=0;i<data.length;i++)
                    {
                          $('#msgid').append(data[i].name_en  + '<br> ');

                    }
                }
            });
        }
    })

I append the result into a div but is always undefined. This is the console.log of my created json:

{"id":"125","name_it":"L&egrave;sina (Hvar)","name_en":"Hvar","nation_id":"23","region_id":"0","active":"1"},{"id":"127","name_it":"Trogir (Tra&ugrave;)","name_en":"Trogir","nation_id":"23","region_id":"0","active":"1"},{"id":"1088","name_it":"Citt&agrave; del Capo","name_en":"Cape Town","nation_id":"101","region_id":"0","active":"1"}]

How to print this json into my success function in javascript? Thanks

1 Answer 1

4

change the datatype:"json" in the ajax will solve the issue

$('#ricerca-ajax').keyup(function(){
        var val = $(this).val();
        if (val.length>2){
            var site_url_city ="<?php echo(site_url('/city/get_city_by_text')); ?>";
            $.ajax({   
                url: site_url_city, 
                type: "POST", 
                data: {search: val},
                dataType: "json",             
                success: function(data) {
                    console.log(data);
                    for(var i=0;i<data.length;i++)
                    {
                          $('#msgid').append(data[i].name  + '<br> ');

                    }
                }
            });
        }
    })
Sign up to request clarification or add additional context in comments.

1 Comment

yes before I was disabled to accept because the time is 15 minutes I think tahnks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.