[development] AJAX return values

Steven Wittens steven at acko.net
Tue May 2 00:55:24 UTC 2006


Dan Robinson schreef:

>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