jquery easy autocomplete url function - javascript

I'm hoping I can get some help on working with jquery easy autocomplete. I am trying to create a url function that calls an html page that has a javascript xmlrpc function, and returns a list of name in json format. All I get in the web console is:WARNING: Fail to load response data.
Query Page:
<html>
<script src="./js/jquery-3.1.1.min.js" type="text/javascript" ></script>
<script src="./js/jquery.xmlrpc.js" type="text/javascript" ></script>
<body>
<p id="display"></p>
</body>
<script>
$(document).ready(function() {
var url = "https://url.to.my.api/nameapi";
$.xmlrpc({
url: url,
methodName: 'API.FullNameQuery',
success: function(response, status, jqXHR) {
var resp = response + '';
document.getElementById('display').innerHTML = resp;
},
error: function(jqXHR, status, error) { console.log("Error getting information:" + error) }
});
});
</script>
</html>
Easy Autocomplete page:
<html>
<script src="./js/jquery-3.1.1.min.js" type="text/javascript" ></script>
<script src="./js/jquery.easy-autocomplete.min.js"></script>
<link rel="stylesheet" href="css/easy-autocomplete.min.css">
<link rel="stylesheet" href="css/easy-autocomplete.themes.min.css">
<body>
<input id="inputOne" placeholder="Full Name" />
<input id="inputTwo" placeholder="netID" />
</body>
<script>
$(document).ready(function() {
var resp;
var options = {
url: function(phrase) {
return phrase !== "" ?
"https://url.to.my.api/get-people.html" :
"https://url.to.my.api/get-people.html";
},
getValue: "fullName",
ajaxSettings: {
dataType: "json"
},
requestDelay: 300,
theme: "blue-light",
list: {
maxNumberOfElements: 200,
match: {
enabled: true
}
}
};
$("#inputOne").easyAutocomplete(options);
});
</script>
</html>
This is hosted on an IIS server, and I can't use php like the examples show for easy autocomplete. The page returns proper json as I have validated it, so I'm a little confused what it doesn't like it.

I had kind of the same problem if I understand correctly.
I wanted to load an array of data only once, which is not how easy autocomplete works. If you use the URL it will do requests once you type letters.
1) : Create an Easy AutoComplete function that load the settings (re-usable is dope) :
function autoComplete(data_src) {
return {
data: loadManufacturer(data_src),
getValue: "name",
theme: "bootstrap",
list: {
match: {
enabled: true
},
showAnimation: {
type: "fade", //normal|slide|fade
time: 200,
callback: function () {}
},
hideAnimation: {
type: "slide", //normal|slide|fade
time: 200,
callback: function () {}
}
}
};
}
2) : Store the datas in a var
function loadManufacturer(url) {
var tmp = null;
$.ajax({
'async': false,
'type': "GET",
'global': false,
'dataType': 'json',
'url': url,
'success': function (data) {
tmp = data;
}
});
return tmp;
}
3) Call your function in an input :
$("#search_product_manufacturer").easyAutocomplete(
autoComplete(
$("#search_product_manufacturer").attr('data-src')
)
);

You are using Duckduckgo search of easyAutocomplete.
Change your code as follows:
var options = {
.....
ajaxSettings: {
data: {
dataType: "jsonp"
}
},
.....
}
for other Ajax setting, read Ajax settings guide

Related

Recursive RestAPI call render data on Datatables looping error

I need to make recursive RestAPI calls to overcome the 5000 view threshold of SharePoint online. Below code goes into a loop after generating the first 5000 entries. It generates the datatable and then increments into displaying the same data in a loop. I totally have only 8800 entries in my SharePoint list.
I just need to generate the 1st batch of 5000 entries and then the second batch of 3800 entries using recursive calls and display the concat data in Jquery Datatables.
$(document).ready(function() {
var table = $('#table_id').DataTable({
"pageLength": 100,
"dom": 'Bfrtip',
"buttons": [searchBuilder, copy],
"aoColumns": [{"mData": "Created"}, {"mData": "EncodedAbsUrl"}]
});
var response = response || [];
var listURL = "SPO_Site/_api/web/lists/getbytitle('List_Name')/items?$top=5000&$select=Created,EncodedAbsUrl";
GetListItemsRecursive(listURL);
function GetListItemsRecursive() {
$.ajax({
url: listURL,
type: "GET",
dataType: "json",
headers: {
"accept": "application/json;odata=verbose"
},
success: mySuccHandler,
error: myErrHandler
});
}
function mySuccHandler(data) {
response = response.concat(data.d.results);
console.log(data);
if (data.d.__next) {GetListItemsRecursive(data.d.__next);}
try {table.rows.add(response).draw();}
catch (e) {alert(e.message);}
}
function myErrHandler(data, errMessage) {alert("Error");}
});
My test cide for your reference:
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.css">
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.js"></script>
<script>
$(document).ready(function () {
var response = response || [];
var listURL = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('testn')/items?$top=5000&$select=ID,Title";
GetListItemsRecursive(listURL);
function GetListItemsRecursive(listURL) {
$.ajax({
url: listURL,
type: "GET",
dataType: "json",
async: false,
headers: {
"accept": "application/json;odata=verbose"
},
success: mySuccHandler,
error: myErrHandler
});
}
function mySuccHandler(data) {
console.log(data)
response = response.concat(data.d.results.map(e=>[e.ID,e.Title]));
console.log(response);
if (data.d.__next) { GetListItemsRecursive(data.d.__next); }
// try { table.rows.add(response).draw(); }
// catch (e) { alert(e.message); }
}
function myErrHandler() {
}
$('#table_id').DataTable({
data: response,
columns: [
{ title: "ID" },
{ title: "Title" }
]
});
})
</script>
<table id="table_id" class="display"></table>
Test result:

Display ajax result from php in jquery popup

I have the following code.
$.ajax({
url: "insert_sp.php",
method: "POST",
data: {submit: 'true'},
success: function(response) {
var data = JSON && JSON.parse(response) || $.parseJSON(response);
alert(data);
}
});
They displayed $ReturnMessage, the result displayed retrieved from PHP using ajax after a new user is being added. Now, I want them to be displayed in a popup.
I've tried some examples on the internet and I figured I need help.
Here's the code :
PHP
<?php
if(isset($_POST['submit']))
{
$UserId=$_POST["UserId"];
$UserPwd=$_POST["UserPwd"];
$stmt = odbc_exec($conn, "CALL UserInsert('$UserId','$UserPwd',)");
if ($stmt) {
if (odbc_fetch_row($stmt)) {
$ReturnStatus=odbc_result($stmt,'ReturnStatus');
$ReturnMessage=odbc_result($stmt,'ReturnMessage');
}
if(isset($ReturnStatus) && $ReturnStatus==1) {
$ReturnMessage=odbc_result($stmt,'ReturnMessage');
}
}
$ReturnMessage = utf8_encode ($ReturnMessage);
echo json_encode($ReturnMessage);
}
?>
Here the script I tried to implement the popup. There is no error but the popup didn't come out.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
Script
function showPopup() {
$("#popup").dialog({
autoOpen: true,
resizable: false,
height: 'auto',
width: 'auto',
modal: true,
draggable: true
});
}
function closePopup() {
$("#popup").dialog('close');
}
function submit(data) {
$.ajax({
url: "insert_sp.php",
method: "POST",
data: {submit: 'true'},
success: function(response) {
{
showPopup();
$('#popup').html(response);
$("#popup").dialog('open');
var data = JSON && JSON.parse(response) || $.parseJSON(response);
alert(data);
}
});
}

TypeError: ui is undefined with jQuery

I a have a Bootstrap Typeahead function, what I want to customize a little bit. If the user clicks on any of the items in the result dropdown list, the user would be redirected to one subpage. The typeahead function is working great, the dropdown list is populated without any error, this is one example what is return from the php file:
[{"name":"TEXT-ONE","url":"\/textone-postfix"},{"name":"TEXT-TWO","url":"\/texttwo-postfix"},{"name":"TEXT-THREE"
,"url":"\/textthree-postfix"}]
The idea is, that the "name" attribute is displayed to the user and after click, it's redirects to the "url" attribute.
The problem is that right now after I click on ANY of the items I get this error (Firefox Firebug console output):
TypeError: ui is undefined
This is my jQuery function and before that the .js imports:
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>
<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
<script src="/bootstrap/js/ie10-viewport-bug-workaround.js"></script>
<script src="/bootstrap/js/bootstrap3-typeahead.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
displayText: function(item) {
return item.value
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
</script>
</body>
Can someone help me please, what's the problem here?
Thank you very much!
updater function was the solution:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
displayText: function(item) {
return item.value
},
updater: function (item) {
window.location.href = item.url
},
});
});
});

select2 ajax not returning correct value in asp.net

I am using Select2 3.5.1
.I have a text box
<asp:TextBox ID="txtSerach" runat="server" ClientIDMode="Static" Width="150px"></asp:TextBox>
which is converted to select2.
I want to pass parameter to my backend to load dynamically result when user click a search Name it will go to back end,fetch data to select,the result will be shown as textbox result
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.1/select2.css" rel="stylesheet" type="text/css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.1/select2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var myurl = 'ajaxOndemandsinSelect2.aspx/getSpareParts';
$('#txtSerach').select2({
ajax: {
url: myurl,
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
type:'POST',
quietMillis: 100,
data: function (term) {
var dt = {
id: "id",
text: "text"
};
return JSON.stringify({ "name":term });
},
results: function (data) {
return {
results: data
};
}
}
});
});
</script>
and my webmethod in asp.net is
[WebMethod]
public static List<Select2Data> getSpareParts(string name)
{
//q 2term 2
var db = new WaltonCrmEntities();
var dataOfSelect= db.SpareParts.Select(x => new Select2Data
{
id = x.ItemID,
text = x.ItemName
}).ToList();
return dataOfSelect;
}
But ajax is not returning correct result !!! see my screen shot

How to get a short snippet of text and the main image of Wikipedia articles by API?

I'm trying to create a simple clone of Wikipedia that allows the user to search for a subject, and then display 10 results that contain the article's image and a short snippet of text. I've been able to pass the user supplied search field to my .ajax() call with no problem. But now I'm unable to retrieve the images, I've read all the other posts on StackOverflow regarding this problem, but have no success.
$(document).ready(function() {
var input = $('input');
var button = $('button');
//Create varialbe to store search field
var toSearch = '';
//Api data:
var searchUrl = 'https://en.wikipedia.org/w/api.php';
//.ajax() to get articles
var ajaxArticle = function() {
$.ajax({
url: searchUrl,
dataType: 'jsonp',
data: {
action: 'query',
format: 'json',
prop: 'extracts',
exchars: '200',
exlimit: 'max',
explaintext: '',
exintro: '',
rawcontinue: '',
generator: 'search',
gsrsearch: toSearch,
gsrnamespace: '0',
gsrlimit: '10'
}, //End data:
success: function(json1) {
console.log(json1);
}
}); //End .ajax()
}
//.ajax() to get images
var ajaxImage = function() {
$.ajax({
url: searchUrl,
dataType: 'jsonp',
data: {
'action': 'query',
'titles': toSearch,
'prop': 'pageimages',
'format': 'json'
}, //End data:
success: function(json2) {
console.log(json2)
}
}); //End .ajax()
}
//Auto complete search bar
input.autocomplete({
source: function(request, response) {
$.ajax({
url: searchUrl,
dataType: 'jsonp',
data: {
'action': "opensearch",
'format': "json",
'search': request.term
},
success: function(data) {
response(data[1]);
}
});
}
}); //End auto compelete
//Listen for click on button to store search field
button.click(function() {
toSearch = input.val();
ajaxArticle();
ajaxImage();
}); //End click handler
})
<html>
<body>
<head>
<title>My Wikipedia Viewer</title>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" />
</head>
<section>
<input type='text' value='' placeholder='Search for...'>
<button>Make it so</button>
</section>
<section class='articles'></section>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
<script type='application/javascript' src='js/script.js'></script>
</html>
I appreciate any help that may be provided.
You can retrieve the text and the images in one request, try this:
$(document).ready(function () {
var articles = $('.articles');
var input = $('input');
var button = $('button');
var toSearch = '';
var searchUrl = 'https://en.wikipedia.org/w/api.php';
var ajaxArticleData = function () {
$.ajax({
url: searchUrl,
dataType: 'jsonp',
data: {
//main parameters
action: 'query',
format: 'json',
generator: 'search',
//parameters for generator
gsrsearch: toSearch,
gsrnamespace: 0,
gsrlimit: 10,
prop: 'extracts|pageimages',
//parameters for extracts
exchars: 200,
exlimit: 'max',
explaintext: true,
exintro: true,
//parameters for pageimages
piprop: 'thumbnail',
pilimit: 'max',
pithumbsize: 200
},
success: function (json) {
var pages = json.query.pages;
$.map(pages, function (page) {
var pageElement = $('<div>');
//get the article title
pageElement.append($('<h2>').append($('<a>').attr('href', 'http://en.wikipedia.org/wiki/' + page.title).text(page.title)));
//get the article image (if exists)
if (page.thumbnail) pageElement.append($('<img>').attr('width', 150).attr('src', page.thumbnail.source));
//get the article text
pageElement.append($('<p>').text(page.extract));
pageElement.append($('<hr>'));
articles.append(pageElement);
});
}
});
};
input.autocomplete({
source: function (request, response) {
$.ajax({
url: searchUrl,
dataType: 'jsonp',
data: {
'action': "opensearch",
'format': "json",
'search': request.term
},
success: function (data) {
response(data[1]);
}
});
}
});
button.click(function () {
articles.empty();
toSearch = input.val();
ajaxArticleData();
});
});
<!DOCTYPE html>
<html>
<head>
<title>My Wikipedia Viewer</title>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" />
</head>
<body>
<section>
<input type='text' value='' placeholder='Search for...'>
<button>Search</button>
</section>
<section class='articles'></section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
</body>
</html>

Categories