[development] AJAX return values

Dan Robinson dan at civicactions.com
Tue May 2 02:41:15 UTC 2006


Steven,

I figured it out last night after getting on #drupal for a moment.  Also
Robert replied off-line.  It is very straight forward.  All of this is
new for me so everything is fairly complicated.  You are right however,
it is very easy.  I had read through the doco (the tutorials) but still
didn't quite "get it" - also they weren't updated with the newer
parseJson call.  Also there is quite a bit of abstraction going on in
the tutorials and in the way that the functions are being declared in
your examples from autocomplete.js (which I had looked at previously) -
this made it relatively difficult for me to figure out what was what.  I
would be happy to take a pass at the doco which I think could be made
simpler. 

Thanks a bunch,

Dan
>
>> thanks for the quick response.  Is there some code you could point me
>> at?
>>  
>>
> The Ajax autocompleter uses JSON to pass in the list of suggestions.
> It's quite simple.
>
> For PHP to JS, you build a PHP variable/array/object and print it
> through drupal_to_js. On the JS side, you take the XMLHttpRequest data
> and pass it through parseJson().
>
> For JS to PHP, we don't use JSON. JS and PHP already have a mechanism
> for passing data in: HTTP GET and POST. Simply use HTTPPost, and pass
> in a JS object. It will be parsed by PHP into a PHP object on the
> server-side. Or, you can pass in simpler requests through HTTP GET.
>
> Either way, there is a transparent mechanism to pass data between PHP
> and JS without loss. It's not as hard as you might think, it all
> happens transparently.
>
> Steven Wittens
>
> Code from user.module:
> ------------------------------------
>
> /**
> * Retrieve a pipe delimited string of autocomplete suggestions for
> existing users
> */
> function user_autocomplete($string) {
>  $matches = array();
>  $result = db_query_range("SELECT name FROM {users} WHERE LOWER(name)
> LIKE LOWER('%s%%')", $string, 0, 10);
>  while ($user = db_fetch_object($result)) {
>    $matches[$user->name] = check_plain($user->name);
>  }
>  print drupal_to_js($matches);
>  exit();
> }
>
>
>
> Code from autocomplete.js:
> ----------------------------------------
>
> /**
> * Performs a cached and delayed search
> */
> ACDB.prototype.search = function(searchString) {
>   ....
>  this.timer = setTimeout(function() {
>    addClass(db.owner.input, 'throbbing');
>    db.transport = HTTPGet(db.uri +'/'+
> encodeURIComponent(searchString), db.receive, db);
>  }, this.delay);
> }
>
> /**
> * HTTP callback function. Passes suggestions to the autocomplete object
> */
> ACDB.prototype.receive = function(string, xmlhttp, acdb) {
> ...
> // Parse back result
>  var matches = parseJson(string);
>  if (typeof matches['status'] == 'undefined' || matches['status'] != 0) {
>    acdb.cache[acdb.searchString] = matches;
>    acdb.owner.found(matches);
>  }
> }
>



More information about the development mailing list