How to jQuery autocomplete with JSON? - javascript

For below JSON
{
"partnerNameListBeanStruts2Map": [
{
"firstName": "sachin",
"partnerId": 123
},
{
"firstName": "Ankit",
"partnerId": 234
}
]
}
What code should I wright to done jQuery autocompleter.
Here is my code.
Here I want autocomplete element's value is like sachin OR ankit and id is like like 123 OR 234 is id of element.
$(document).ready(function() {
$(function() {
$("#search").autocomplete({
source : function(request, response) {
$.ajax({
url : "list.action",
type : "POST",
data : {
term : request.term
},
dataType : "json",
success : function(data)
{
****What should I write here to work my code?****
}
});
}
});
});

According to the doc, You should return your data with the response callback function.
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
$(function($) {
$("#search").autocomplete({
source : function(request, response) {
$.ajax({
url : "list.action",
type : "POST",
data : {
term : request.term
},
dataType : "json",
success : function(data)
{
***response (data) ;***
}
});
}
});
});

Related

Sending a JSON object to Django backend through AJAX call

I have the following code (jQuery) to create a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
item.Code : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now this is my AJAX function:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ //I need my items object, how do I send it to backend server (django)??
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Now, my doubt is how do I send the 'item[]' object that I created to the backend? I do need to send both the item[] object and the variable 'calltype' which signals what made the AJAX call, as I have the same Django View (its the Controller equivalent for Django) in the backend being called by different AJAX functions.
How will my AJAX function look like?
Hey guys just got my answer right.
I used the following ajax function to get it right:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: items,
calltype: 'save',
'csrfmiddlewaretoken': csrf_token},
dataType: 'json',
// handle a successful response
success : function(jsondata) {
console.log(jsondata); // log the returned json to the console
alert(jsondata['name']);
},
// handle a non-successful response
error : function() {
console.log("Error"); // provide a bit more info about the error to the console
}
});
}());
So, this is sort of a self answer!!! :) Thanks a lot SO!!

Get JSON data with AJAX and then modify raphael.js script

This is what I want to achieve:
I want to create an interactive map using raphael.js.
Using Php, I get datas from MySql DB and converted into a JSON file.
So far so good.
Inside my raphael js file, I must now:
get those datas
use them in order to modify my raphael file.
I am currently stuck at this first step.
Here's my simplified JSON file (let's call it countries.json) :
[
{
"id": "1",
"type": "Country",
"title": "France",
"published": "1",
"description": "Republic"
},
{
"id": "2",
"type": "Country",
"title": "Belgium",
"published": "0",
"description": "Monarchy"
}
]
Here comes the simplified raphael.js
var rsr = Raphael('map', '548', '852');
var countries = [];
var france = rsr.path("M ... z");
france.data({'published': '1', 'type': '', 'title': '', 'description':''});
var belgium = rsr.path("M ... z");
belgium.data({'published': '0', 'type': '', 'title': '', 'description':''});
countries.push(france,belgium);
At the end of the raphael js, I make an Ajax request (using jquery) to get my JSON datas :
$.ajax({
type : 'GET',
url : 'system/modules/countries.json',
data: {get_param: 'value'},
dataType : 'json',
success : function(data, statut){
console.log(statut);
},
error : function(data, statut,erreur){
console.log(statut);
},
complete: function (data) {
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
}
});
Here come the troubles:
I get a 'success' status trough the success function.
BUT I got an error while completing the script :
Uncaught SyntaxError: Unexpected token o
What did I miss? Can't figure out what is different from http://jsfiddle.net/fyxZt/4/ (see how to parse json data with jquery / javascript?)
That was just for part 1 :-)
Assuming someone could help me to fix that, I still then have no idea how to write js loop that will set the raphael vars attributes as it:
var rsr = Raphael('map', '548', '852');
var countries = [];
var france = rsr.path("M ... z");
france.data({'published': '1', 'type': 'Country', 'title': 'France', 'description':'Country'});
var belgium = rsr.path("M ... z");
belgium.data({'published': '0', 'type': 'Country', 'title': 'Belgium', 'description':'Monarchy'});
communes.push(france,belgium);
Thanks an advance for your help and please excuse my unperfect english!
Vinny
There is no data argument passed to the complete callback,
according to jQuery API:
complete
Type: Function( jqXHR jqXHR, String textStatus )
(...)The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror").
So you only need to use the success callback :
$.ajax({
type: 'GET',
url: 'system/modules/countries.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function (data, statut) {
var json = data;
$(json)
.each(function (i, val) {
$.each(val, function (k, v) {
console.log(k + " : " + v);
});
});
},
error: function (data, statut, erreur) {
console.log(statut);
}
});
Concerning your second question, you cannot interact directly with variable name (accessing dynamic variable) in js, so you'll need to create an object where values are indexed by one of your json's values. However, the cleanest way to handle this would probably be to add your paths to the json...
var rsr = Raphael('map', '548', '852');
var countries = [];
//here I used the "id" property from the json
var paths={
"1":rsr.path("M ... z"),
"2":rsr.path("M ... z")
};
countries.push(france,belgium);
$.ajax({
type: 'GET',
url: 'system/modules/countries.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function (data, statut) {
datas.forEach(function (country) {
paths[country.id].data(country);
});
},
error: function (data, statut, erreur) {
console.log(statut);
}
});

jquery autocomplete with ajax source does not retrieve results

I have the following autocomplete that pulls from my ajax data source:
$("#id_q").autocomplete({
source: function (request, response) {
$.ajax({
url: "/search/autocomplete/",
dataType: "jsonp",
data: {
q: request.term
},
success: function (data) {
alert(data);
response(data);
}
});
},
minLength: 3,
select: function (event, ui) {
log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
Server side I can see that results are being returned correctly and look like:
{"results": ["BEEF", "BEEFARONI", "BEEFARONI", "BEEF", "BEET"]}
The success method never fires the alert.
Also should I rename request.term?
What am I doing wrong and where can I print the data I am returning to figure out what is going on?
Do you pass data to source method?
Is your url correct? I think yours is wrong, try writing the whole URL or use a REST client to check it.
Thanks for the hint #Andrew Whitaker . I removed the entire dataType line and it worked.

Populating a JSTree with JSON data obtained in AJAX

I'm trying to populate a JSTree with JSON data that I'm obtaining from a service (which is called using ajax). However, I am getting a "Neither data nor ajax settings supplied error" in the jquery.jstree.js file. Because of this the JSTree just displays a loading gif.
AJAX code (editted to try setting json to local variable test, then return test)
function getJSONData() {
var test;
$
.ajax({
async : true,
type : "GET",
url : "/JavaTestService/rs/TestService/MyFirstTestService?languageCode=en_US&version=2",
dataType : "json",
success : function(json) {
test = json;
},
error : function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
test = "error";
}
});
return test;
}
JSTree code
var jsonData = getJSONData();
createJSTrees(jsonData);
function createJSTrees(jsonData) {
$("#supplierResults").jstree({
"json_data" : {
"data" : jsonData
},
"plugins" : [ "themes", "json_data", "ui" ]
});
After some debugging, I've found that jsonData is undefined when passed to the createJSTrees method. Am I retrieving that data correctly in the Ajax code?
Thanks in advance
jsonData is undefined because getJSONData() doesn't return a value. You can't rely on the return value from your $.ajax success handler unless you assign a variable local to getJSONData() that gets returned after the $.ajax call completes. But you want something like this, which also has the benefit of being asynchronous:
<script type="text/javascript">
$(function() {
$.ajax({
async : true,
type : "GET",
url : "/JavaTestService/rs/TestService/MyFirstTestService?languageCode=en_US&version=2",
dataType : "json",
success : function(json) {
createJSTrees(json);
},
error : function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
function createJSTrees(jsonData) {
$("#supplierResults").jstree({
"json_data" : {
"data" : jsonData
},
"plugins" : [ "themes", "json_data", "ui" ]
});
}
</script>
I have not tested your approach before, where you supply the data parameter directly to the json_data plugin, so I won't be able to supply an answer to this scenario.
However, since you are using an AJAX call to get the data, can't you supply the AJAX call to JSTree and let it handle the call on its own? Here's how I've configured the AJAX call in my code:
(...)
'json_data': {
'ajax': {
'url': myURL,
'type': 'GET',
'data': function(node) {
return {
'nodeId': node.attr ? node.attr("id") : ''
};
}
},
'progressive_render': true,
'progressive_unload': false
},
(...)

jQuery autocomplete - pass targeted element attribute as an extra parameter?

I'm using the jQuery UI Autocomplete plug-in to make an ajax call and retrieve data. As well as passing the text of the input element I'm trying to pass in the 'id' attribute of the input element as an additional parameter. An extract of my code looks like this -
$("#autocomplete input").autocomplete({
source: function(request, response) {
$.ajax({
url: "search.php",
dataType: "json",
data: {
term: extractLast(request.term),
extra_param: $(this).attr('id')
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.label,
value: item.name
}
}))
}
})
},
});
The extra parameter is added to the 'data' property in the ajax call. It works okay if I specifically pass in a value e.g. '3' but I want to pass the 'id' attribute of the input element the function is being called on e.g. $(this).attr('id').
I assume it's a problem with 'this' not being evaluated in this part of the code, but I'm at a loss to see how else I can reference the element that is being targeted. Any help appreciated!
$('#autocomplete input').each(e, function() {
$(e).autocomplete('/path?param=' + $(e).attr('id'), function() { ... });
});
$('#autocomplete input').each(e, function() {
$(e).autocomplete({ source:function ... extra_param: $(e).attr('id') ... });
});
There maybe a more elegant way, but, I know autocomplete is somewhat sophisticated. I personally generate the request w/get parameters and use formatItem/formatResult instead of assigning the source to an ajax call.
I've got it working by breaking the autocomplete call out into an each. This allows me to capture the target element before I execute the autocomplete -
$("#autocomplete input").each(function() {
var that = this;
$(that).autocomplete({
source: function(request, response, this_element) {
$.ajax({
url: "search.php",
dataType: "json",
data: {
term: extractLast(request.term),
extra_param: $(that).attr('id')
}
....
"Source" is the ID of your input, you receive this item and save it in the variable, "that". When the input "Source" calls the autocomplete function, you can send the value of your id stored in the variable "that" for AJAX.
Example:
<script type="text/javascript">
$(document).ready(function() {
$("#Source").each(function() {
var that = this;
var url = "<?php echo constant('URL'); ?>";
$(that).autocomplete({
source: function(request, response){
$.ajax({
url: url+"models/queries/C_getOptions.php",
dataType:"json",
data:{
word:request.term,
id : $(that).attr('id')
},
success: function(data){
response(data);
}
});
},
minLength: 1,
select: function(event,ui){
//alert("Selecciono: "+ ui.item.label);
}
});
})
});

Categories

Resources