jquery Autocomplete - not filtering - javascript

I am trying to user JQuery autocomplete function with an ajax call in it, which will return the list of Strings..when i am trying to type, it is showing all the list of strings and not filtering out based on the input..Not sure where i am going wrong..Below is my autocomplete function..
$("#domainNameId").autocomplete({
source : function(request, response) {
console.log("in ajax ");
$.ajax({
url : "getAllDomains",
type : "GET",
contentType : "application/json",
data : {
env : $("#environment").val()
},
dataType : "json",
success : function(data) {
response(data); // list of strings..
},
error : function(x, t, m) {
console.trace();
if (!(console == 'undefined')) {
console.log("ERROR: " + x + t + m);
}
console.log(" At the end");
}
});
},
});
appreciate the help..

Your backend seems to always return the entire data and not do any filtering ( The service name itself is getAllDomains). In that case there is no need to use the function form of source option to make ajax calls.
What you're doing is sending multiple AJAX requests to the server as the user types. If your backend always returns the same data, there is no point in sending multiple requests to it. You can simply fetch the data once and then initialize the autocomplete with the response as source, then the widget will do the filtering as user types.
The docs says:
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.
So if your server doesn't do the filtering, don't use the function form to make AJAX requests.
do something like:
$(function() {
// make a one-time request
$.ajax({
url: "getAllDomains",
type: "GET",
contentType: "application/json",
dataType: "json",
success: function(data) {
// init the widget with response data and let it do the filtering
$("#domainNameId").autocomplete({
source: data
});
},
error: function(x, t, m) {
console.trace();
if (!(console == 'undefined')) {
console.log("ERROR: " + x + t + m);
}
console.log(" At the end");
}
});
});

In the success callback, you will need to filter the data yourself using the request.term passed to the source function.
There is more information on the jQuery Autocomplete source here: https://api.jqueryui.com/autocomplete/#option-source.

Related

CRUD Operation using NAPA in SharePoint 2013

I am completely new to SharePoint development.
I am trying to create an app for basic CRUD operation using NAPA.
I took the reference from http://www.plusconsulting.com/blog/2013/05/crud-on-list-items-using-rest-services-jquery/.
There are some basic get commands in REST.
I am using Get All List Items From a Single List (where url is like: http://UsersrverName/site/_api/web/lists/getbytitle(‘listname’)/items)
Now for getting list items based on ODATA Query, the function is:
function getListItems(url, listname, query, complete, failure) {
// Executing our items via an ajax request
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
complete(data); // Returns JSON collection of the results
},
error: function (data) {
failure(data);
}
});
}
here, as per function arguments, I have assigned the value for url and listname, query is blank as I am selecting all items, and I have no idea what to assign for complete and failure.
So my main concern is the arguments to be passed in the function getListItems().
Kindly help. and if there is any other alternative (without using REST), then please suggest.
Basically complete and failure arguments are function callbacks. The following example demonstrates how to call the specified function:
var webUrl = 'http://intranet.contoso.com';
var listTitle = 'Documents';
var queryOptions = '';
getListItems(webUrl,listTitle ,queryOptions,
function(data){ //success callback function
for(var i = 0; i < data.d.results.length; i++){
var item = data.d.results[i];
console.log(item.Title);
}
},
function(error){ //error callback function
console.log(JSON.stringify(error));
}
);
Key points:
SharePoint REST endpoint /_api/web/lists/getbytitle('<list title>')/items returns JSON object in the following format:
(for Documents library)
Another approach that is commonly used and was introduced in jQuery 1.5 is based on the CommonJS Promises/A design:
jQuery.Deferred() provides flexible ways to provide multiple
callbacks, and these callbacks can be invoked regardless of whether
the original callback dispatch has already occurred
The same example that demonstrates how to utilize jQuery.Deferred() object:
function getListItems(url, listname, query) {
return $.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items" + query,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" }
});
}
Usage
getListItems(_spPageContextInfo.webAbsoluteUrl,'Documents','')
.done(function(data)
{
for(var i = 0; i < data.d.results.length; i++){
var item = data.d.results[i];
console.log(item.Title);
}
})
.fail(
function(error){
console.log(JSON.stringify(error));
});

Display search results from API

Hello there I'm trying to create an app to search for recipes. I've tried using the Yummly API and BigOven api, but I can't get either to work.
here is the code i have for bigOven. I can't get any search results to appear in the "results".
$(function() {
$('#searchform').submit(function() {
var searchterms = $("#searchterms").val();
// call our search twitter function
getResultsFromYouTube(searchterms);
return false;
});
});
function getResultsFromYouTube (searchterms) {
var apiKey = "dvxveCJB1QugC806d29k1cE6x23Nt64O";
var titleKeyword = "lasagna";
var url = "http://api.bigoven.com/recipes?pg=1&rpp=25&title_kw="+ searchterms + "&api_key="+apiKey;
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
alert('success');
console.log(data);
$("#results").html(data);
}
});
}
Can anyone give me instructions on how to do this?? Thank you very much.
The API is returning JSON data, not HTML. I checked the API docs, and JSONP isn't necessary.
However, when you run this code:
$('#results').html(data);
Your code is going to just put the JSON into your HTML, and that isn't going to get displayed properly. You didn't say whether console.log(data) outputs the data correctly, but I'll assume it is.
So, you'll need to transform your JSON into HTML. You can do that programmatically, or you can use a templating language. There are a number of options, including underscore, jquery, mustache and handlebars.
I recommend handlebars, but it's not a straightforward bit of code to add (the main difficulty will be loading your template, or including it in your build).
http://handlebarsjs.com/
It would depend on you which key and values you have to show to your user's and in which manner... For ex. there is even an image link, you could either show that image to your user's or could just show them the image link...
Simple <p> structure of all the key's with there value's
jQuery
$.each(data.Results, function (key, value) {
$.each(value, function (key, value) {
$("#result").append('<p>Key:-' + key + ' Value:-' + value + '</p>');
});
$("#result").append('<hr/>');
});
Your ajax is working, you just need to parse the results. To get you started:
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
// Parse the data:
var resultsString = "";
for (var i in data.Results){
console.log( data.Results[i] );
resultsString+= "<div>"+data.Results[i].Title+ " ("+data.Results[i].Cuisine+")</div>";
}
$("#results").html(resultsString);
// If you want to see the raw JSON displayed on the webpage, use this instead:
//$("#results").html( JSON.stringify(data) );
}
});
I had created a little recursive function that iterates through JSON and spits out all of the values (I subbed my output for yours in the else condition) -
function propertyTest(currentObject, key) {
for (var property in currentObject) {
if (typeof currentObject[property] === "object") {
propertyTest(currentObject[property], property);
} else {
$('#results').append(property + ' -- ' + currentObject[property] + '<br />');
}
}
}
Then I called it within your AJAX success -
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
console.log(data);
propertyTest(data); // called the function
}
});
It spits out all of the data in the JSON as seen here - http://jsfiddle.net/jayblanchard/2E9jb/3/

Parallel Ajax Calls in Javascript/jQuery

I am completely new to Javascript/jquery world and need some help. Right now, I am writing one html page where I have to make 5 different Ajax calls to get the data to plot graphs. Right now, I am calling these 5 ajax calls like this:
$(document).ready(function() {
area0Obj = $.parseJSON($.ajax({
url : url0,
async : false,
dataType : 'json'
}).responseText);
area1Obj = $.parseJSON($.ajax({
url : url1,
async : false,
dataType : 'json'
}).responseText);
.
.
.
area4Obj = $.parseJSON($.ajax({
url : url4,
async : false,
dataType : 'json'
}).responseText);
// some code for generating graphs
)} // closing the document ready function
My problem is that in above scenario, all the ajax calls are going serially. That is, after 1 call is complete 2 starts, when 2 completes 3 starts and so on .. Each Ajax call is taking roughly around 5 - 6 sec to get the data, which makes the over all page to be loaded in around 30 sec.
I tried making the async type as true but in that case I dont get the data immediately to plot the graph which defeats my purpose.
My question is:
How can I make these calls parallel, so that I start getting all this data parallely and my page could be loaded in less time?
Thanks in advance.
Using jQuery.when (deferreds):
$.when( $.ajax("/req1"), $.ajax("/req2"), $.ajax("/req3") ).then(function(resp1, resp2, resp3){
// plot graph using data from resp1, resp2 & resp3
});
callback function only called when all 3 ajax calls are completed.
You can't do that using async: false - the code executes synchronously, as you already know (i.e. an operation won't start until the previous one has finished).
You will want to set async: true (or just omit it - by default it's true). Then define a callback function for each AJAX call. Inside each callback, add the received data to an array. Then, check whether all the data has been loaded (arrayOfJsonObjects.length == 5). If it has, call a function to do whatever you want with the data.
Let's try to do it in this way:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var area0Obj = {responseText:''};
var area1Obj = {responseText:''};
var area2Obj = {responseText:''};
var url0 = 'http://someurl/url0/';
var url1 = 'http://someurl/url1/';
var url2 = 'http://someurl/url2/';
var getData = function(someURL, place) {
$.ajax({
type : 'POST',
dataType : 'json',
url : someURL,
success : function(data) {
place.responseText = data;
console.log(place);
}
});
}
getData(url0, area0Obj);
getData(url1, area1Obj);
getData(url2, area2Obj);
});
</script>
if server side will be smth. like this:
public function url0() {
$answer = array(
array('smth' => 1, 'ope' => 'one'),
array('smth' => 8, 'ope' => 'two'),
array('smth' => 5, 'ope' => 'three')
);
die(json_encode($answer));
}
public function url1() {
$answer = array('one','two','three');
die(json_encode($answer));
}
public function url2() {
$answer = 'one ,two, three';
die(json_encode($answer));
}
So there, as you can see, created one function getData() for getting data from server and than it called 3 times. Results will be received in asynchronous way so, for example, first can get answer for third call and last for first call.
Console answer will be:
[{"smth":1,"ope":"one"},{"smth":8,"ope":"two"},{"smth":5,"ope":"three"}]
["one","two","three"]
"one ,two, three"
PS. please read this: http://api.jquery.com/jQuery.ajax/ there you can clearly see info about async. There default async param value = true.
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active...
The following worked for me - I had multiple ajax calls with the need to pass a serialised object:
var args1 = {
"table": "users",
"order": " ORDER BY id DESC ",
"local_domain":""
}
var args2 = {
"table": "parts",
"order": " ORDER BY date DESC ",
"local_domain":""
}
$.when(
$.ajax({
url: args1.local_domain + '/my/restful',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST",
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(args1),
error: function(err1) {
alert('(Call 1)An error just happened...' + JSON.stringify(err1));
}
}),
$.ajax({
url: args2.local_domain + '/my/restful',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
type: "POST",
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(args2),
error: function(err2) {
calert('(Call 2)An error just happened...' + JSON.stringify(err2));
}
})
).then(function( data1, data2 ) {
data1 = cleanDataString(data1);
data2 = cleanDataString(data2);
data1.forEach(function(e){
console.log("ids" + e.id)
});
data2.forEach(function(e){
console.log("dates" + e.date)
});
})
function cleanDataString(data){
data = decodeURIComponent(data);
// next if statement was only used because I got additional object on the back of my JSON object
// parsed it out while serialised and then added back closing 2 brackets
if(data !== undefined && data.toString().includes('}],success,')){
temp = data.toString().split('}],success,');
data = temp[0] + '}]';
}
data = JSON.parse(data);
return data; // return parsed object
}
In jQuery.ajax you should provide a callback method as below:
j.ajax({
url : url0,
async : true,
dataType : 'json',
success:function(data){
console.log(data);
}
}
or you can directly use
jQuery.getJSON(url0, function(data){
console.log(data);
});
reference
You won't be able to handle it like your example. Setting to async uses another thread to make the request on and lets your application continue.
In this case you should utilize a new function that will plot an area out, then use the callback functions of the ajax request to pass the data to that function.
For example:
$(document).ready(function() {
function plotArea(data, status, jqXHR) {
// access the graph object and apply the data.
var area_data = $.parseJSON(data);
}
$.ajax({
url : url0,
async : false,
dataType : 'json',
success: poltArea
});
$.ajax({
url : url1,
async : false,
dataType : 'json',
success: poltArea
});
$.ajax({
url : url4,
async : false,
dataType : 'json',
success: poltArea
});
// some code for generating graphs
}); // closing the document ready function
It looks like you need to dispatch your request asynchronously and define a callback function to get the response.
The way you did, it'll wait until the variable is successfully assigned (meaning: the response has just arrived) until it proceeds to dispatch the next request. Just use something like this.
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(data) {
area0Obj = data;
}
});
This should do the trick.
Here's a solution to your issue: http://jsfiddle.net/YZuD9/
you may combine all the functionality of the different ajax functions into 1 ajax function, or from 1 ajax function, call the other functions (they would be private/controller side in this case) and then return the result. Ajax calls do stall a bit, so minimizing them is the way to go.
you can also make the ajax functions asynchronous (which then would behave like normal functions), then you can render the graph at the end, after all the functions return their data.

Passing an array to a web method in Javascript

I am currently trying to pass an array that I have created in Javascript to my webmethod in my aspx.cs.
Heres what I have:
JAVASCRIPT
function callServer(requestMethod, clientRequest) {
var pageMethod = "Default.aspx/" + requestMethod;
$.ajax({
url: pageMethod, // Current Page, Method
data: JSON.stringify({ request: clientRequest }), // parameter map as JSON
type: "POST", // data has to be POSTed
contentType: "application/json", // posting JSON content
dataType: "JSON", // type of data is JSON (must be upper case!)
timeout: 60000, // AJAX timeout
success: function (result) {
ajaxCallback(result.d);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
}
function myButtonCalls()
{
var values=[];
values[0] = "Hello";
values[1] = "goodbye";
callServer("myMethod", values);
}
ASPX.CS
[WebMethod]
public static string myMethod(string[] request)
{
return "This is test";
}
It fails before it even gets to my web method. I know this code works for regualr strings but The ajax code that uses JSON doesnt see to want to work with arrays.
Any ideas of what i need to change?
Thanks
In the aspx.cs, I needed to accept with type list not array. Thanks for the comments!

Array of Objects via JSON and jQuery to Selectbox

I have problems transferring a dataset (array of objects) from a servlet to a jsp/jquery.
This is the dataset sent by the servlet (Json):
[
{aktion:"ac1", id:"26"},
{aktion:"ac2", id:"1"},
{aktion:"ac3", id:"16"},
{aktion:"ac4", id:"2"}
]
The jsp:
function getSelectContent($selectID) {
alert('test');
$.ajax({
url:'ShowOverviewDOC',
type:'GET',
data: 'q=getAktionenAsDropdown',
dataType: 'json',
error: function() {
alert('Error loading json data!');
},
success: function(json){
var output = '';
for (p in json) {
$('#'+$selectID).append($('<option>').text(json[p].aktion).attr('value', json[p].aktion));
}
}});
};
If I try to run this the Error ('Error loading json data') is alerted.
Has someone an idea where the mistake may be?
Thanks!
If the error function is running, then your server is returning an error response (HTTP response code >= 400).
To see exactly what is going on, check the textStatus and errorThrown information that is provided by the error callback. That might help narrow it down.
http://api.jquery.com/jQuery.ajax/
The way you are setting the data parameter looks a bit suspect (notice JSON encoding in my example below). Here is how it would look calling a .Net asmx
$.ajax({
url: "/_layouts/DashboardService.asmx/MinimizeWidgetState",
data: "{'widgetType':'" + widgetType + "', 'isMinimized':'" + collapsed + "'}"
});
Also the return data is by default placed in the .d property of the return variable. You can change this default behavior by adding some ajax setup script.
//Global AJAX Setup, sets default properties for ajax calls. Allows browsers to make use of native JSON parsing (if present)
//and resolves issues with certain ASP.NET AJAX services pulling data from the ".d" attribute.
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
success: function(msg) {
if (this.console && typeof console.log != "undefined")
console.log(msg);
},
dataFilter: function(data) {
var msg;
//If there's native JSON parsing then use it.
if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
//If the data is stuck in the "."d" property then go find it.
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
handleAjaxError(XMLHttpRequest, textStatus, errorThrown);
}
});

Categories

Resources