Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>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.</p> <p>I was converting an object (say Product) to JSON by using json_encode. The Product class also implements the <strong>JsonSerializable</strong> interface which consists of one function, <strong>jsonSerialize()</strong>.</p> <p>My implementation for jsonSerialize() in the orginal post was longer, but I finally have it sort of like this:</p> <pre><code>function jsonSerialize() { return [ 'id' =&gt; $this-&gt;id, 'label' =&gt; $this-&gt;name ]; } </code></pre> <p>For autocomplete to work with an object or actually anything more than a one-dimensional array, you will need to have either a <strong>'label'</strong> or <strong>'value'</strong> 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.</p> <p>This is how my actual <strong>autocomplete function</strong> looks:</p> <pre><code>$("#product_search").autocomplete({ source: "./includes/search_products.php", minLength: 1, select: function(event, ui) { /* Do something */ } }); </code></pre> <p>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.</p> <p><strong>Solution:</strong></p> <pre><code>if(!is_array($product)) $product = array($product); </code></pre> <p>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.</p> <p>Over and out.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload