2

JSON data not added in jQuery array

$(function() {
  $(document).ready(function() {
    $.get("automcomplete.php", function(data, status) {
      console.log(data);
      // echo json_encode($result['name']);
      // response 
      // "Afghanistan""Africa""Albania""Algeria"

      var availableTags = [data];
      // i want todo this 
      // var availableTags = [
      //    "america",
      //    "london"
      //   ];
      $("#tags").autocomplete({
        source: availableTags
      });
    });
  });
});
<div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>

Create auto complete list dynamically and show in the list problem is how i can put json data in jquery array

9
  • I wonder why do u have both $(function(){}) and $(document).ready(); they are one and the same. and directly assign data to availableTags Commented Aug 10, 2017 at 11:58
  • Also add dataType argument or use $.getJSON to be sure data is parsed Commented Aug 10, 2017 at 11:59
  • Show the php. Looks like you might have multiple echo in a loop and need to create an array and only echo once Commented Aug 10, 2017 at 12:03
  • @RahulNaik i am new in jquery so did not notice Commented Aug 10, 2017 at 12:41
  • @charlietfl only single echo if (isset($result_array)) { foreach ($result_array as $result) { echo json_encode($result['name'] ); }} Commented Aug 10, 2017 at 12:43

1 Answer 1

1

Your PHP code indicates that you're returning JSON, so you can just remove var availableTags = [data]; and give data directly to the source property:

$(function() {
  $.get("automcomplete.php", function(data) {
    $("#tags").autocomplete({
      source: data
    });
  });
});

If your data is returned as a string, you can manually parse it to an object using JSON.parse():

$.get("automcomplete.php", function(data) {
  var sourceData = JSON.parse(data);
  $("#tags").autocomplete({
    source: sourceData
  });
});

Note that you don't need two document.ready handlers. A single $(function() {}); is enough

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

2 Comments

That's down to what your server returns. Presumably you need to amend the AJAX so you can send the search term and then your automcomplete.php should perform the search logic.
my repsonse is "Afghanistan""Africa""Albania""Algeria" and i need reponse like this "Afghanistan","Africa","Albania","Algeria" but how i add comma after every single country i think thats why its not work perfect

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.