Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Well there are a couple things that I would change and a couple things you are doing right. First your post request can encode the json all by it's self. Take a look at your line </p> <pre><code>$.post('phpPage.php', { /*no matter*/ }, showResult, "text"); </code></pre> <p>and change it to </p> <pre><code>$.post('phpPage.php', { /*no matter*/ }, showResult, "json"); </code></pre> <p>jQuery will parse the json and turn it into an object.</p> <p>Now for an explanation, when you use <code>encode_json()</code> with php it does not create a json object all php does is format at an array like an object for JS to then turn into json.</p> <p>What you are doing with <code>JSON.parse</code> is taking the string that php returns that will probably look like this </p> <pre><code>{"1":"jquery", "2":"AJAX","3":"JSON"} </code></pre> <p>with your example, and turning it into an object in JS.</p> <p>Now for the important part. Objects in JS can be treated as an associative array, this means that they are array where the key is the index. So manipulation of an object or traversing an object can be very easy. </p> <p>So you have the function <code>showResult(res)</code> if you want to traverse the json object and print results to the screen its pretty darn easy. First I want to change your for loop to a <code>for...in</code> then we just use your json object like an array</p> <pre><code>function showResult(res){ var obj = JSON.parse(res); $("input#autocomplete").autocomplete({ source: function() { var rows = new Array(); for (x in obj){//Assume that I know array size, skip it $('body').append(obj[x]+'&lt;br&gt;'); } return rows; } }); } </code></pre> <p>The only thing I changed in your code is </p> <pre><code>for (x in obj){//Assume that I know array size, skip it $('body').append(obj[x]+'&lt;br&gt;'); } </code></pre> <p>This will traverse the array and plug in the correct key where x is to use every single value of the json object and add it to the body on a new line.</p> <p>Now to use it with autocomplete is what ever those plugin docs say. I hope this helps you a little.</p>
    singulars
    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.
    1. VO
      singulars
      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