0

Currently I'm trying to load in the content of a select with an AJAX call. To do this I have an AJAX that sends a request to my controller and returns the response.Now this does return the response, but it also shows an error saying JSON.parse: unexpected character at line 1 column 2 of the JSON data. Here is what it shows in console:

Now the following is the code I'm using to achieve this:

console log image

View Class:

<label for="code" class="control-labels text-nowrap mr-3">Search Contacts</label>
<input id="owners"  name="owners_det" list="owners_list" placeholder="Start typing to show contacts" value="<?php echo $owner_details; ?>" type="text">
<input type="hidden" name="owners_id" id="owners_id" value="<?php echo $owner_id; ?>" />
<datalist id="owners_list">
</datalist>

AJAX:

function getcontacts(obj){
  var dataString = new Object();
  $.ajax({
        type: "GET",
        dataType:"json",
        url: "<?php echo site_url('listings/getContacts'); ?>/"+obj,
        success: function(response){
            console.log(response);
            var responseText = JSON.parse(response);
            $('#owners_list').html(responseText,data);
        }
    });  
}

Controller Class:

public function getContacts($id){

    $option = "<option value='0'>Select</option>";

    $modelList = $this->listings_model->get_contact('firstname,lastname,mobile,email,agents_id,title,id,refno');  
    foreach($modelList as $m){
        $option .= "<option value='".$m['firstname']." ".$m['lastname']." - ".$m['refno']."' id='".$m['id']."'>".$m['firstname']." ".$m['lastname']." - ".$m['refno']."</option>";
    }
    $data = array(
        'data' => $option
    );
    echo json_encode($data);
}

It seems that a data entry has a unusable character and the data is too big for me to try and find that character. So I was thinking if it would be possible to convert this into a JSON format instead?

JAYZ
  • 9
  • 4
  • I do not endorse generating html markup in a controller as a shortcut. Iterate your data in the view jquery/js to build the options -- there is dedicated syntax for this. There is no benefit in duplicating the option's text as the `value` attribute -- just remove the markup bloat. As for the `id`, do you actually want `data-id`? It is unusual to `id` an option. Please provide Debugging Details as text -- what is the generated data that breaks your code? – mickmackusa Nov 25 '21 at 17:50
  • Try removing `JSON.parse()`, that looks unnecessary. Try accessing `response.data` directly. – mickmackusa Nov 25 '21 at 17:56
  • You have `dataType:"json"` and call `JSON.parse`. They must not be used together. Accessing js object properties is done with dots, not commas. – mickmackusa Nov 25 '21 at 18:09
  • Finally, I don't see `for="code"` relating to an `id` attributes in your html. You probably need to adjust that to point to an existing `id`. – mickmackusa Nov 25 '21 at 18:13

0 Answers0