JQuery AutoComplete From XML (Dynamic Results) - javascript

Perhaps I'm not understanding this concept (I'm an AJAX/javascript/Web newbie). I'm using the JQuery autocomplete feature and if I specify a small, limited items flat file (suggestions.xml) the function works fine, but when I use an actual production data file (3 MB) of suggestions the script doesn't work at all.
So I created a web service that generates XML based on the characters in the textbox but it appears this JQuery doesn't run on each keypress, rather only when the page first loads. Obviously, for this function to be of any use it needs to fetch results dynamically as the user types into the input field.
$(document).ready(function () {
var myArr = [];
$.ajax({
type: "GET",
// this line always sends the default text; not what the user is typing
url: "Suggestions.aspx?searchString=" + $("input#txtSearch").val(),
dataType: "xml",
success: parseXml,
complete: setupAC,
failure: function (data) {
alert("XML File could not be found");
}
});
function parseXml(xml) {
//find every query value
$(xml).find("result").each(function () {
myArr.push({ url: $(this).attr("url"), label: $(this).attr("name") + ' (' + $(this).attr("type").toLowerCase() + ')' });
});
}
function setupAC() {
$("input#txtSearch").autocomplete({
source: myArr,
minLength: 3,
select: function (event, ui) {
$("input#txtSearch").val(ui.item.label);
window.location.href = ui.item.url;
//alert(ui.item.url + " - " + ui.item.label);
}
});
}
});
On the server I expected to see a few requests corresponding to the characters the user is typing into the search box but instead I get a single message:
2013-10-18 22:02:04,588 [11] DEBUG baileysoft.mp3cms.Site - QueryString params: [searchString]:'Search'
My flat file of suggestions appears to be way to large for JQuery to handle and my web service script is never called, except when the page is first loaded.
How do I generate suggestions dynamically as the user is typing in the search box if I can't run back to the database (via my web service) to fetch suggestions as the user is typing?

Ok, I got it all worked out.
On the ASPNET side; I created a form to receive and respond to the AJAX:
Response.ContentType = "application/json";
var term = Request.Form["term"];
var suggestions = GetSuggestions(term); // Database results
if (suggestions.Count < 1)
return;
var serializer = new JavaScriptSerializer();
Response.Write(serializer.Serialize(suggestions);
On the AJAX side I modified the js function:
$("input#txtSearch").autocomplete({
minLength: 3,
source: function (request, response) {
$.ajax({
url: "Suggestions.aspx",
data: { term: $("input#txtSearch").val() },
dataType: "json",
type: "POST",
success: function (data) {
response($.map(data, function (obj) {
return {
label: obj.Name,
value: obj.Url
};
}));
}
});
},
select: function (event, ui) {
$("input#txtSearch").val(ui.item.label);
window.location.href = ui.item.value;
}
});
Everything is working as expected now.
Hope this helps someone else who might get stuck trying to figure out JQuery stuff for ASPNET.

Related

Adding to JSON array by HTML button

I have an AJAX call, as below. This posts data from a form to JSON. I then take the values and put them back into the div called response so as to not refresh the page.
$("form").on("submit", function(event) { $targetElement = $('#response'); event.preventDefault(); // Perform ajax call // console.log("Sending data: " + $(this).serialize()); $.ajax({
url: '/OAH',
data: $('form').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
// Success handler
var TableTing = response["table"];
$("#RearPillarNS").empty();
$("#RearPillarNS").append("Rear Pillar Assembly Part No: " + response["RearPillarNS"]);
$("#TableThing").empty();
$("#TableThing").append(TableTing);
for (key in response) {
if (key == 'myList') {
// Add the new elements from 'myList' to the form
$targetElement.empty();
select = $('<select id="mySelect" class="form-control" onchange="myFunction()"></select>');
response[key].forEach(function(item) {
select.append($('<option>').text(item));
});
$targetElement.html(select);
} else {
// Update existing controls to those of the response.
$(':input[name="' + key + '"]').val(response[key]);
}
}
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call }) });
This generates a new <select id="mySelect">
I need to now extract the value that has been selected by the newly generated select and amend my JSON array. Again, without refreshing the page.
I was thinking of doing this via a button called CreateDrawing
The JS function for this would be:
> $(function() {
$('a#CreateDrawing').bind('click', function() {
$.getJSON('/Printit',
function(data) {
//do nothing
});
return false;
});
});
This is because I will be using the data from the JSON array in a Python function, via Flask that'll be using the value from the select.
My question is, what is the best way (if someone could do a working example too that'd help me A LOT) to get the value from the select as above, and bring into Python Flask/JSON.

ajax call based on the value of 2 input fields to populate jquery autocomplete

I have been stuck with this problem for a while. I would like to pass 2 arguments (the value of 2 input fields of one form) in my ajax call to be used for a jquery autocomplete (the search is based on a mysql query using the values of input1 and input2). I had a few suggestions but so far i have no luck:
here my ajax call trying to pass the 2 arguments input1 and input2. there is no code error showing up but the autocomplete does not work. it is working if i am using only one argument.
function fillbox2(){
$('#input2').autocomplete({
source: function(request, response ){
var frmStr={
input1:$('#input1').val(),
input2:$('#input2').val()
requestTerm: request.term
};
$.ajax({
url: './cgi_temp3.cgi',
dataType: 'json',
data:{data: frmStr},
contentType: "application/json; charset=utf-8",
success: function (data) {
response ($.map( data.matches, function(item){
return {
value: item.info2,
}
}));
}
});
},
minLength: 2,
select: function(event, ui){
$("#prod_term").val(ui.item.value);
return false;
}
});
and here my cgi script that process the MYSQL query
#!/usr/local/bin/python3
import cgi, json
import os
import mysql.connector
def main():
print("Content-Type: application/json\n\n")
form = cgi.FieldStorage()
term2 = form.getvalue('input2')
term1=form.getvalue('input1')
conn = mysql.connector.connect(user='***', password='***', host='localhost', database='***')
cursor = conn.cursor()
qry = """
SELECT name2, info2
FROM table2
join table1 ON
info2_id=information2_id
WHERE name2 LIKE %s AND info2_id=%s
"""
cursor.execute(qry, ('%' + term2 + '%',term1))
where could be the problem?
At first glance I'd say it's possibly a timing issue. The source function isn't going to wait for your ajax call to complete, so you're essentially giving it a blank value. Try initiating the autocomplete inside the ajax success function.
function fillbox2(){
$.ajax({
...
success: function (data) {
...
$('#input2').autocomplete(...);
});
}

Javascript works fine with a hard-coded string but not with variable

I have a problem I have bee struggling over all morning so I felt it was time to get some help! I have a javascript function which gets the value entered by a user into an autocomplete box, uses AJAX to send that value to a php script which queries the database and then populates the following box with the possible options. The problem is this all works fine when I hard-code in the selected option as so:
var selected="Ed Clancy";
but not when it pulls it from the box, as so:
var selected = this.getValue();
I have tried debugging this using an alert box and both boxes come up with the same string in them so I am completely puzzled! Any ideas? Full code below:
$(riderSelected).on('selectionchange', function(event){
var selected = this.getValue();
//var selected="Ed Clancy";
alert(selected);
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$('#nap4').append($("<option>-select-</option>"));
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: { name: selected },
success: function(data) {
console.log(data);
$('#nap4').append(data);
}
});
});
Based on magicsuggest documentation - http://nicolasbize.com/magicsuggest/doc.html , you probably could do this
var selected = this.getValue()[0];
IF you do not allow multiple selection
Change your code as I have written below for you .
Code
$(riderSelected).on('change', function (event) {
var selected = this.value;
alert(selected);
$('#nap4').removeAttr('disabled');
$('#nap4').empty();
$('#nap4').append($("<option>-select-</option>"));
$.ajax({
type: "GET",
url: 'getbiketype.php',
data: {name: selected},
success: function (data) {
console.log(data);
$('#nap4').append(data);
}
});
});

Dynamic html elements show only when going through debugger

I'm working on project that simulates Twitter and I'm using HTML + JS on client and WCF services on server side (ajax calls), and Neo4J as database.
For example:
in $(document).ready(function ()
there is DisplayTweets service call -> DisplayTweets(username)
function DisplayTweets(userName) {
$.ajax(
{
type: "GET", //GET or POST or PUT or DELETE verb
url: "Service.svc/DisplayTweets", // Location of the service
data: { userName: userName },
contentType: "application/json; charset=utf-8", // content type sent to server
dataType: "json",
processdata: true, //True or False
success: function (msg) //On Successfull service call
{
DisplayTweetsSucceeded(msg);
},
error: function () // When Service call fails
{
alert("DISPLAY TWEETS ERROR");
}
}
);
}
and then DisplayTweetsSucceeded(msg) where msg would be json array of users tweets
function DisplayTweetsSucceeded(result)
{
for (var i = 0; i < result.length; i++)
{
var tweet = JSON.parse(result[i]);
var id_tweet = tweet.id;
var content_tweet = tweet.content;
var r_count_tweet = tweet.r_count;
NewTweet(null, id_tweet, content_tweet, r_count_tweet);
}
}
Function NewTweet is used for dynamic generating of tweets.
Problem is when I first load html page, nothing shows up, neither when I load it multiple times again. It only shows when I go through Firebug, line by line.
I'm presuming that maybe getting data from database is slower, but I'm not sure and also have no idea how to solve this. Any help will be very much appreciated, thank you in advance!

Navigation in javascript widget using JSONP

I am working on javascript widget which can be shown on any site.
see.
Show JS(jQuery) widget on any site, with ASP.NET MVC server side
Embeddable widgets using jQuery and ASP.NET MVC
and for now I faced with issue, when I need to navigate between pages in widgets. See code below. But for now I am confused how to organize navigation (link clicking, ajax updating) in html that comes from server, to make it working as without widget, because I want to debug it as usual page.
<img alt="TEST" onclick="window.zs.LoadStep1('ad507a69-d882-41d4-8300-bd9f7163d419',this);" style="cursor:pointer;"/>
;
(function (window, ZS, undefined) {
var zs = window.zs = ZS || {};
zs.Version = "v1_0";
zs.baseUrl = "http://localhost/w/";
var jQueryScriptOutputted = false;
var containerSelector = '#zaprosWidgetContainer';
function initJQuery() {
if (typeof (jQuery) == 'undefined') {
if (!jQueryScriptOutputted) {
jQueryScriptOutputted = true;
document.write("<scr" + "ipt type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js\"></scr" + "ipt>");
}
setTimeout("initJQuery()", 50);
}
};
function initContainer() {
if ($(containerSelector).length == 0) {
$('<div id="zaprosWidgetContainer" style="width=500px;height:500px;"></div>').appendTo('body');
}
}
zs.LoadStep2 = function (serviceId) {
$.ajax({
url: zs.baseUrl + 'Wizard/Step2JsonP?jsoncallback=?',
data: { serviceId: serviceId },
type: "GET",
dataType: "jsonp",
jsonpCallback: "callBack",
success: function (json) {
$(containerSelector).html(json.Html);
}
});
},
zs.LoadStep1 = function (providerId) {
$(function () {
$.ajax({
url: zs.baseUrl + 'Wizard/Step1JsonP?jsoncallback=?',
data: { providerId: providerId },
type: "GET",
dataType: "jsonp",
jsonpCallback: "callBack",
success: function (json) {
$(containerSelector).html(json.Html);
}
});
});
};
initJQuery();
initContainer();
})(window, window.zs || {});
I understand that you want to navigate to LoadStep1/LoadStep2 without ajax-style?
You could create a master page in ASP.NET that has a link/button to navigate to the next step. That link is generated as part of the previous step.
E.g. on the output html of Step1 add
Next Step
Can you tell us why you have to create a "non-widget mode" for debugging? What's the difference for debugging?
Something else about JsonP that helped me:
You can also extend your JsonP class that wraps the JSON data into a JsonP string to support returning normal JSON when no callback method is supplied - this way you can use the same uri to return the html directly. I use that to allow widgets run in JsonP and Json simultaneously.

Categories