Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to get tag-it to work with an AJAX call

Trying to get tag-it to work with an ajax call.

Everything works so far. Except, I am unable to assign a tagSource via an ajax call.

In firebug, the 'data' is returning:

["Ruby","Ruby On Rails"] 

But its not showing up as I type into the input box.

$('.tags ul').tagit({   itemName: 'question',   fieldName: 'tags',   removeConfirmation: true,   availableTags: ["c++", "java", "php", "javascript", "ruby", "python", "c"],   allowSpaces: true,   // tagSource: ['foo', 'bar']   tagSource: function() {     $.ajax({       url:        "/autocomplete_tags.json",       dataType:   "json",       data:       { term: 'ruby' },       success:    function(data) {         console.log(data);         return data;       }     });   } }); 

console.log(data) returns ["Ruby", "Ruby On Rails"].

Am I missing something here? Anyone else got this to work?

like image 678
Christian Fazzini Avatar asked Aug 04 '11 09:08

Christian Fazzini


People also ask

Does AJAX work with HTML?

AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files.

How do I load HTML in AJAX?

load(URL,data,callback); The required URL parameter specifies the URL you wish to load. The optional data parameter specifies a set of querystring key/value pairs to send along with the request. The optional callback parameter is the name of a function to be executed after the load() method is completed.

Can I do AJAX call in JavaScript?

Ajax is a programming concept. Below are some ways to make Ajax call in JavaScript. Approach 1: In this approach, we will use the XMLHttpRequest object to make Ajax call. The XMLHttpRequest() method which create XMLHttpRequest object which is used to make request with server.


2 Answers

Seems this question hasn't been answered for a long time, I bet you have already found a solution but for those who haven't here is my answer:

The indention got all messed up when i copied from my code ;)

<input type="hidden" name="tags" id="mySingleField" value="Apple, Orange" disabled="true"> Tags:<br> <ul id="mytags"></ul>  <script type="text/javascript">     jQuery(document).ready(function() {     jQuery("#mytags").tagit({         singleField: true,         singleFieldNode: $('#mySingleField'),         allowSpaces: true,         minLength: 2,         removeConfirmation: true,         tagSource: function( request, response ) {             //console.log("1");             $.ajax({                 url: "search.php",                  data: { term:request.term },                 dataType: "json",                 success: function( data ) {                     response( $.map( data, function( item ) {                         return {                             label: item.label+" ("+ item.id +")",                             value: item.value                         }                     }));                 }             });         }});     }); 

and the "search.php" you can find this in some autocomplete jQuery examples actually.

<?php $q = strtolower($_GET["term"]); if (!$q) return;  $items = array(     "Great Bittern"=>"Botaurus stellaris",     "Little Grebe"=>"Tachybaptus ruficollis",     "Black-necked Grebe"=>"Podiceps nigricollis",     "Little Bittern"=>"Ixobrychus minutus",     "Black-crowned Night Heron"=>"Nycticorax nycticorax",     "Heuglin's Gull"=>"Larus heuglini" );  function array_to_json( $array ){      if( !is_array( $array ) ){         return false;     }      $associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));     if( $associative ){          $construct = array();         foreach( $array as $key => $value ){          // We first copy each key/value pair into a staging array,         // formatting each key and value properly as we go.          // Format the key:         if( is_numeric($key) ){             $key = "key_$key";         }         $key = "\"".addslashes($key)."\"";          // Format the value:         if( is_array( $value )){             $value = array_to_json( $value );         } else if( !is_numeric( $value ) || is_string( $value ) ){             $value = "\"".addslashes($value)."\"";         }          // Add to staging array:         $construct[] = "$key: $value";     }      // Then we collapse the staging array into the JSON form:     $result = "{ " . implode( ", ", $construct ) . " }";  } else { // If the array is a vector (not associative):      $construct = array();     foreach( $array as $value ){          // Format the value:         if( is_array( $value )){             $value = array_to_json( $value );         } else if( !is_numeric( $value ) || is_string( $value ) ){             $value = "'".addslashes($value)."'";         }          // Add to staging array:         $construct[] = $value;     }      // Then we collapse the staging array into the JSON form:     $result = "[ " . implode( ", ", $construct ) . " ]"; }  return $result; }  $result = array(); foreach ($items as $key=>$value) {     if (strpos(strtolower($key), $q) !== false) {     array_push($result, array("id"=>$value, "label"=>$key, "value" => strip_tags($key))); } if (count($result) > 11)     break; } echo array_to_json($result);  ?> 
like image 136
Ekim Avatar answered Oct 05 '22 23:10

Ekim


check this out: How to get tagSource to work with $.ajax()? (from tag-it's github issue list).

this is an example: HTML file:

<!doctype html> <html lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript" charset="utf-8"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript" charset="utf-8"></script> <script src="js/tag-it.js" type="text/javascript" charset="utf-8"></script> <link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/flick/jquery-ui.css"> <link href="css/jquery.tagit.css" rel="stylesheet" type="text/css">  <script type="text/javascript"> $(document).ready(function() { $("#mytags").tagit({   tagSource: function(search, showChoices) {     $.ajax({       url: "auto.php",       data: {search: search.term},       success: function(choices) {         showChoices(choices);       }     });   } }); }); </script> </head> <body> <ul id="mytags"> <li>Tag1</li> </ul> </body> </html> 

(get tag-it.js file from [here][1])

and this is the PHP file:

<?php header('Content-type: application/json'); $q = $_GET["search"]; //check $q, get results from your database and put them in $arr $arr[] = 'tag1'; $arr[] = 'tag2'; $arr[] = $q; echo json_encode($arr); ?> 
like image 44
Kambiz Avatar answered Oct 05 '22 21:10

Kambiz