jquery - autocomplete url - javascript

I'm using jQuery autocomplete in my web application. I followed this http://jqueryui.com/demos/autocomplete/#remote-jsonp When it sends the suggestion request it sending to the different url not the one I've given in $.ajax() url
Here is the jQuery code:
$("#add-keywords").autocomplete({
source: function( request, response ) {
var q = $("#add-keywords").val();
$.ajax({
url: "keywords_suggestions/",
dataType: "json",
data: {
query: q
}
});
},
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
}
});
I'm using Django for server side scripting. It must actually want to request to this url http://127.0.0.1:8000/keywords_suggestions But it requesting to this url http://127.0.0.1:8000/information/?query=web Why is it so?
Thanks!

I was having the same problem and resolved it by loading the latest jquery and jqueryUI files.
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
Earlier i was using only the autocomplete.min.js taken up from some website. May be that was the problem

Either it doesn't like the URL, or the given one doesn't exist anyways try to put a / before the url url: "/keywords_suggestions/" maybe this will help.
Otherwhise take a look if you have a different autocomplete on the same site if it get's triggered unintentionally by your function - as you said it's going to a different url then specified -> try to find out what kind of url it is - and how it could possibly be redirected there.

Related

JQuery Autocomplete source not updating

I am using jquery-ui autocomplete plugin.
Here is how I've instantiated the autocomplete plugin.
//autofill
$( "#TextArea" ).autocomplete({
source: "search.php?option="+ option.toLowerCase(),
minLength: 3
});
On dropdown change, i am trying to change the option :
$('#Options').on('change', function() {
option = this.value.toLowerCase();
var teaxtarea = $('#TextArea');
//this is supposed to change the source string when the option value changes.
teaxtarea.autocomplete( "option", "source", "search.php?option="+ option);
}
});
I got the code to update the source string from the question below.
Jquery: Possible to dynamically change source of Autocomplete widget?
However, this solution doesn't seem to work for me.
I still get the first selected option even if i change the option in the dropdown.
Any help is greatly appreciated.
Suggest the following:
$("#TextArea").autocomplete({
source: function(req, resp){
var option = $('#Options option:selected').val().toLowerCase();
$.ajax({
cache: false,
url: "search.php",
data: {
option: option,
term: req.term
},
dataType: "json",
success: function(data){
resp(data);
}
});
},
minLength: 3
});
I think one issue is that if #Options is a <select> element, you need to find the selected child element:
$("#Options option:selected")
This ensures that you have the proper object and then you can call .val() upon it. If you need more help here, please update your post with an MCVE: https://stackoverflow.com/help/mcve
That may resolve the issue for you. If not, continue on.
Second, to ensure you are not caching, we can perform a more manual source capture.
When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must support CORS). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results.
So we replicate the same functionality with some added settings. So each time source is checked, the options will be checked and the term will be sent. We'll get the data back in JSON and send back to Autocomplete to be displayed.
Hope that helps.

Ajax call after page load

I am trying to build a search page where the user inputs text into a search box and the page is generated based on the search. I am having timing issues because the blank search page is loading after the JS tries to edit the values on the page.
$.ajax({
type: 'GET',
url: '/index.php/content/generate_search',
data: {
search: input.val()
},
beforeSend: function() {
window.location.href = '/index.php/content/search';
},
success: function() {
$('.hero h1').text(input.val());
}
});
To check that the DOM is completely loaded, many steps have to be done taking all the browsers into consideration. (I cannot find the implementation in the jQuery source, but I will come back with a link).
The easiest and probably best way of doing it, since you're already using jQuery is by:
$( function() {
// your code here
} );
which is a shorthand for
$( document ).ready( function() {
// your code here
} );
EDIT
Ok, so as I promised, I came back with the implementation of document.ready. You can find it here, on GitHub. Here is a permanent link to the current version of the file.
Try this:
$(document).ready(function(){
//Your code
});
onload is used for executing code on pageload
window.onload = function() {
// your code
};
This code:
beforeSend: function() {
window.location.href = "/index.php/content/search";
},
… is causing the browser to leave the page and load a new one before it sends the Ajax request.
Consequently, the Ajax request gets cancelled. If it didn't, then there would be no JavaScript waiting to receive the response.
If you want to visit /index.php/content/search and then initiate an Ajax request, then the JavaScript to initiate the Ajax request has to be on /index.php/content/search. A page you've just left can't run JavaScript on the next page.

How to initiate controller/action in CFWheels, for Ajax?

I have been trying to get cfwheels to work with FineUploader for two days now, and I just can't figure out how to force the jQuery script to execute a Controller/Action. This is how far I've come so far:
$(document).ready(function() {
var restricteduploader = new qq.FineUploader({
// Since we're using jQuery, use the jQuery way to select the HTML element
element: $('##restricted-fine-uploader')[0],
request: {
type: "POST",
url: $(this).attr("href") + "/index.cfm?controller=users&action=UploadFileXhr&format=json", // References "/say/hello?format=json"
dataType: "json",
endpoint: '/index.cfm?controller=users&action=UploadFileXhr&format=json'
},
multiple: false,
validation: {
allowedExtensions: ['jpeg', 'jpg', 'txt'],
sizeLimit: 5120000000 // 50 kB = 50 * 1024 bytes
},
text: {
uploadButton: 'Click or Drop'
},
showMessage: function(message) {
// Using Twitter Bootstrap's classes and jQuery selector and method
$('##restricted-fine-uploader').append('<div class="alert alert-error">' + message + '</div>');
},
debug: true
});
});
The CFWheels documentation says I have to use this to get an asynchronous request:
(function($){$(document).ready(function(){
// Listen to the "click" event of the "alert-button" link and make an AJAX request
$("#alert-button").click(function() {
$.ajax({
type: "POST",
url: $(this).attr("href") + "?format=json", // References "/say/hello?format=json"
dataType: "json",
success: function(response) {
$("h1").html(response.message);
$("p").html(response.time);
}
});
return false; // keeps the normal request from firing
});
});})(jQuery);
These three lines is what I'm trying to incorporate into my code (because that's what I think I need):
type: "POST",
url: $(this).attr("href") + "?format=json", // References "/say/hello?format=json"
dataType: "json",
But everything I've tried has not worked. I can't even work on my actual upload code to get that to work, since I can't even get the uploader to initiate the required controller/action.
Hopefully someone will be able to point me in the right direction. Thank you!
Question also posted to cfWheels mailing list: https://groups.google.com/forum/?fromgroups=#!topic/cfwheels/UKk_57y9ncQ
I'm not familiar with FineUploader, but normally when I am doing AJAX requests in Wheels, I use the urlFor() function to build the correct controller/action location.
CFWheels - urlFor
I think I know what problem you're facing. Follow these steps:
Make sure in your controller Say.cfc provides the JSON format to the Ajax call:
In the init() function of Say.cfc, make sure to add this:
<cffunction name="init" hint="It secures component from invalid access">
<!--- this is necessary --->
<cfset provides("json") />
</cffunction>
Now, in the hello action, render the data you want to provide without layout. Remove any <cfabort> tags present inside the action:
<!--- this will go at the very end of the action --->
<!--- here the attribute data is the data you want to serve: a query, struct or any other custom data generated inside a `<cfsavecontent>` --->
<cfset renderWith(data=data,layout=false) />
I hope this works for you.

Iterate over the data to show Autocomplete suggestions

This is an API which returns results in an array, for auto suggestions
For Eg. if I query "google" I get the results as follows
["google","google maps","google translate","google earth","google images","google docs","google voice","google scholar","google chrome","google calendar",]
You can try it yourself here
Here's my code that I m using to query this API but it doesnt seem to return results.
Here's the code that I m using for it
$(function() {
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "q.php",
dataType: "json",
data: {
"q" : request.term
},
success: function( data ) {
response(data[1]);
}
});
},
minLength: 2
});
});
I dont understand where am I going wrong in the code
Please correct me ! Because it doesnt seem to be working as I wanted
Edit: Accessing the Data from the same server
You forgot to add jquery-ui library in your fiddle. But if you do code will not work anyway, because you can't access data from another domain via ajax request. Only from same domain on what js code executes.
This might be helpful
$(document).ready(function() {
$.getJSON('http://twitter.com/users/usejquery.json?callback=?', function(json) { //get information about the user usejquery from twitter api
$('#twitter_followers').text(json.followers_count); //get the follower_count from the json object and put it in a span
});
});
Look for something called as cross-domain ajax.
http://usejquery.com/posts/the-jquery-cross-domain-ajax-guide
You can read here about using jQuery autocomlete for cross-domain environment: http://1300grams.com/2009/08/17/jquery-autocomplete-with-json-jsonp-support-and-overriding-the-default-search-parameter-q/
Also you need to add jquery.autocomplete.js to your jsFiddle environment.

Jquery autocomplete with jquery 1.4

Referring to this post and this one. I'm trying to implement tag search for my blog/website something similar to SO tag system using jquery autocomplete plugin, I'm using jquery 1.4 latest version so I'm not sure whether it works with it or not, I've used this plugin before once. So without further jibr-jabr here is my html for autocomplete :
<input id="post-tags" class="ac_input" type="text" autocomplete="off" value="" name="post_tags"/>
Here is my javascript:
<script type="text/javascript">
$(document).ready(function(){
function findValueCallback(event, data, formatted) {
$("<li>").html( !data ? "No match!" : "Selected: " + formatted).appendTo("#result");
}
function formatItem(row) {
return row[0] + " (<strong>id: " + row[1] + "</strong>)";
}
function formatResult(row) {
return row[0].replace(/(<.+?>)/gi, '');
}
$("#post_tags").autocomplete("http://localhost/tags/filter/", {
width: 260,
selectFirst: false
});
$("#clear").click(function() {
$(":input").unautocomplete();
});
});
</script>
I'm sure my php part is ok, it works like this when I manualy type the url http://localhost/tags/filter/p
I returns the following :
php (1)
asp (1)
Meaning all tags containing p, for now I have only these two. My question is, what am I doing wrong, I'm really stuck on this one, I've changed things around so many times now I can't think of anything new I'd like to do. Thank you
The trick is to use post instead of get, when using get / gets erased but when using post complete thing is passed so the autocomplete needs some adjustments(extra one line) here it is :
$.ajax({
type: "post", // This is the new line
// try to leverage ajaxQueue plugin to abort previous requests
mode: "abort",
// limit abortion to this input
Everything worked like a charm now..

Categories

Resources