I am basically building a common autocomplete search bar where a supposed user writes something, jQuery returns a list of suggestions and the user picks one.
My AJAX call looks like this:
var response = '';
var request = $.ajax({
url: "./includes/search_products.php",
type: "post",
dataType: "json",
data: serializedData,
success : function(text) {
response = text; // Gets the list of suggestions
}
});
The response is:
{"id":"2",
"companyId":"15",
"productTypeId":"1",
"label":"Alfa Romeo 159",
"price":"50000","comments":
"Random comment."}
How I set the .autocomplete:
request.done(function (){
console.log("Works.");
$('#product_search').autocomplete({
source: response,
minLength: 1,
select: function(event, ui) {
alert("yey");
}
});
});
The error message that I get is:
TypeError: this.source is not a function
I believe that a normal response should have less quotation marks, based on what the PHP json_encode() documentation says.
What’s the problem? 🙁
Ok, I have found the solution after 2 days. I hope that it will help somebody, someday. No AJAX is worth 8 hours of swearing. This is not a tutorial, but it covers some of the problems that I had in order to get to a working version.
I was converting an object (say Product) to JSON by using json_encode. The Product class also implements the JsonSerializable interface which consists of one function, jsonSerialize().
My implementation for jsonSerialize() in the orginal post was longer, but I finally have it sort of like this:
For autocomplete to work with an object or actually anything more than a one-dimensional array, you will need to have either a ‘label’ or ‘value’ field. The labels will be displayed as the autocomplete suggestions, but the label will be displayed in the input when you select one of the labels.
This is how my actual autocomplete function looks:
My problem was that I was returning a single object with json_encode($product). What I want to say is that $product = new Product(…). It appears that the source option of the autocomplete function requires an array of Products, not just a single one.
Solution:
My code was not wrong in the original post, just these two lines were missing from my PHP script in order for everything to be fine.
Over and out.