1

I am adding the jQuery Autocomplete plugin to my project. I have a source value which is an array of objects (from a mySQL database). I am unable to map them into desired format of autocomplete.

This is the data want to map:

[{
  "value": "730",
  "label": "iPhone"
}, {
  "value": "731",
  "label": "Screen Protector"
}, {
  "value": "732",
  "label": "Maxboost"
}, {
  "value": "733",
  "label": "JETech"
}, {
  "value": "734",
  "label": "Mr Shield"
}]
$("#product_one").autocomplete({
  source: $.ajax({
    type: "GET",
    url: "/wp-json/product/product-info/",
    success: function(res) {
      $.each(res, function(key, val) {
        return {
          "label": val.label,
          "value": val.value
        }
      });
    }
  });
});

Any suggestion or modification of question would be appreciated.

2 Answers 2

1

The issue is because you're providing source with a jqXHR object, not an array, string or function as it expects (docs)

Given the use of AJAX, it would make the most sense for you to use provide a function which uses the request and response arguments. Also note that as the data you retrieve is already in the correct format (ie. an array of objects with label and value properties), you can provide it directly to response() without needing to loop through it. Try this:

$("#product_one").autocomplete({
  source: function(request, response) {
    $.ajax({
      type: "GET",
      url: "/wp-json/product/product-info/",
      success: function(data) {
        response(data);
      }
    });
  }
});
Sign up to request clarification or add additional context in comments.

2 Comments

One more query i have regarding this @Rory McCrossan, i want to display the some output on the change event of autocomplete so, how can i do ?
If I've understood what you're asking, that should happen by default. If you have a specific issue with how the autocomplete is working, I'd suggest starting a new question
0

You should first load your data and then set them as the source of the autocomplete.

$.ajax({               
      type:"GET",
      url: "/wp-json/product/product-info/",
      success:function(res){

           //Based on your object creation, it looks that you can directly use the response
           $( "#product_one" ).autocomplete(res);   

      }
});

Comments

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.