How to call a ajax autocomplete function? - ajax

How to call the ajax auto complete when particular time?
here this is my code
function auto(x){
x.autocomplete('ajax/getFriends',{
max:500,
width:300,
minChars:2,
autoFill: false,
formatItem: formatItem,
formatResult: formatResult
});
function formatItem(row) {
return row[0];
//return row[0] + " (<strong>id: " + row[1] + "</strong>)";
}
function formatResult(row) {
return row[0].replace(/(<.+?>)/gi, '');
}
$("#comment").result(function(event, data, formatted) {
$("#test1").val(data[1]);
$("#test2").val(data[2]);
});
}
but it says error x.autocomplete is not a function
i am calling the above is like
auto("string");
can any one help me how to solve this one
Thanks in advance
i am not good in english if any mistakes excuse me

I think you are confusing the way jQuery autocomplete works alltogether. It seems to me that you are attaching autocomplete to your string and building up the HTML elements for the suggestions. This is not how the autocomplete functionality works.
What you want to do is attach the autocomplete functionality to your input box. Then whenever something is entered in there the autocomplete function fires automatically on the input. That's just how it's built.
So let's say for instance you have an input box with an ID equal to myAwesomeInputBox in your HTML code:
<input type="text" id="myAwesomeInputBox"/>
To bind autocomplete (with ajax) to this input field just do this in Javascript:
$("#myAwesomeInputBox").autocomplete({
source: function( request, response ) {
// request.term is the input in the textbox, encode for security reasons
var input = encodeURI(request.term);
$.ajax({
// your ajax endpoint
url: 'ajax/getFriends',
// the request method, modify to your actual method
type: 'GET',
// whatever data you want to pass to your endpoint.
// I'm assuming at least the input (with key userInput here)
// and maybe the limit of the elements in the response array
// the server should send back
data: {userInput: input, limit: 500},
// what to do on success (process the response)
success: function(data){
// assuming your ajax endpoint returns a JSON encoded array with the suggestions as a response
var responseArray = $.parseJSON(data);
// pass the decoded response array to the jquery defined response method for autocomplete
response(responseArray);
},
// what to do if the server returns an error
error: function(jqXHR, textStatus, errorThrown){
// pass an empty suggestions array maybe?
response(new Array());
}
}, 'json');
}
});
The tricky part for me was
response(responseArray);
but once you examine it it's quite understandable. You're just passing an array to the jQuery autocomplete handler for further processing.
I'm not sure how previous versions of jQuery handled ajax autocomplete but this is how version 1.8.0 (and up) handles it.

Related

passing data to jquery modal aside from adding parameters to url?

On click of a #dtDelete button I am opening an ajax modal in bootstrap 3. I am also passing a parameter, selected, along with it and using $_GET on the php page to retrieve it.
As the value of selected may or may not be extremely large I think I should avoid passing the value this way / using $_GET.
How the heck can I pass values other than this method? Due to the nature of opening the modal (loading it then showing it) I am stuck on any other ways.
$('#dtDelete').on('click', function () {
//open the modal with selected parameter attached
$('#modal-ajax').load('/modals/m_keystroke_delete.php?selected='+selected);
$('#modal-ajax').modal('show');
});
Pass a data object as a second param to load for it to make a POST request.
$('#dtDelete').on('click', function () {
var data = { 'propertyA': 'extremely large data' };
//open the modal with selected parameter attached
$('#modal-ajax').load(
'/modals/m_keystroke_delete.php?selected=' + selected, // url
data, // data
function(responseText, textStatus, XMLHttpRequest) { } // complete callback
);
$('#modal-ajax').modal('show');
});
You can even pass your "selected" param through the POST request and use $_POST or even $_REQUEST to retrieve the data. Also notice that the modal now shows once the request has completed.
$('#dtDelete').on('click', function () {
var data = {
'selected': selected
'largeData': '...'
};
$('#modal-ajax').load(
'/modals/m_keystroke_delete.php',
data,
function() {
// Invoke the delete-function
deleteComp();
// Show the modal
$(this).modal('show');
}
);
});

Ajax URL # isn't updating

I have a little problem with my script here. For some reason, it doesn't enable the #-tags and I don't know why. I created this javascript using the help of this tutorial. (The loading of the pages works well with no problems at all.)
Could someone please look it over and tell me why it doesn't work?
var default_content="";
$(document).ready(function(){ //executed after the page has loaded
checkURL(); //check if the URL has a reference to a page and load it
$('ul li a').click(function (e){ //traverse through all our navigation links..
checkURL(this.hash); //.. and assign them a new onclick event, using their own hash as a parameter (#page1 for example)
});
setInterval("checkURL()",250); //check for a change in the URL every 250 ms to detect if the history buttons have been used
});
var lasturl=""; //here we store the current URL hash
function checkURL(hash)
{
if(!hash) hash=window.location.hash; //if no parameter is provided, use the hash value from the current address
if(hash != lasturl) // if the hash value has changed
{
lasturl=hash; //update the current hash
loadPage(hash); // and load the new page
}
}
function loadPage(url) //the function that loads pages via AJAX
{
// Instead of stripping off #page, only
// strip off the # to use the rest of the URL
url=url.replace('#','');
$('#loading').css('visibility','visible'); //show the rotating gif animation
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0) //if no errors
{
$('#content').html(msg); //load the returned html into pageContet
} $('#loading').css('visibility','hidden');//and hide the rotating gif
}
});
}
You can simplify this immensely by adding a function to listen to the hashchange event, like this:
$(window).on("hashchange", function() {
loadPage(window.location.hash);
});
This way you don't need to deal with timers or overriding click events on anchors.
You also don't need to keep track of lasthash since the hashchange even will only fire when the hash changes.

ajax call not responding with $.post

What i am trying to do is to get the value of the selected elements by jquery selection. After that, those value are post to php script via ajax and then retrieve the data from the database and display it on the same page (something called autocompete).
var marvalue=$("input[name=m_status]:checked").val();
var fromhvalue=$("#fromheight").val();
var tohvalue=$("#toheight").val();
var value = $("#edu_det1").val();
alert (value);
var regvalue = $("#religion").val();
alert (regvalue);
var occvalue = $("#occupation").val();
alert (occvalue);
var convalue = $("#country").val();
alert (convalue);
Alert is there to check the correct values. As you see the code above this will get the values from the different input elements.
Below is the code i used to post to php
/*
$.post("regsearch.php", {queryString: ""+value+"",queryString1: ""+marvalue+"",queryStringfage: ""+fage+"",queryStringtage: ""+tage+""+queryStringfromh: ""+fromhvalue+""+queryStringtoh: ""+tohvalue+""+}, function(data) { // Do an AJAX call
$('#suggestions').fadeIn(); // Show the suggestions box
$('#suggestions').html(data); // Fill the suggestions box
});
*/
The problem :
when the comment is removed nor the alert popup and neither the result displayed. Ok about the result as no query is posted.
Major part is that when i use the below code which hold only m_status and edu_det1 it works.
marvalue=$("input[name=m_status]:checked").val();
alert (marvalue);
var value = $("#edu_det1").val();
alert (value);
The post code for above is
$.post("regsearch.php", {
queryString: ""+value+"",
queryString1: ""+marvalue+"",
queryStringfage: ""+fage+"",queryStringtage: ""+tage+""
}, function(data) {
// Do an AJAX call
$('#suggestions').fadeIn(); // Show the suggestions box
$('#suggestions').html(data); // Fill the suggestions box
});
The code for age and it verification is not added here. What is the problem and how to sort this out?
It will be better if you use jquery serialize() function. This will make your life easier to work with forms.
var querstring = $(form).serialize();
above will help
I guess using ajax post jQuery.ajax() will do the same thing and you can even serialize the fields in your page.
http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings
I have done similar type of code
UserName is the field Which I am passing
var data = $('#Username').serialize();
$('#usernameCheck').empty();
if (!$("form").validate().element("#Username"))
return;
$.ajax({
url: '/SignUp/CheckUsername',
type: 'POST',
data: data,
async: true,
success: function (result) {
if (result == 1) {
$('#usernameCheck').html('<font color=green>Username available</font>');
usernameOK = true;
}
else if (result == 2) {
$('#usernameCheck').html('<font color=red>Username not available</font>');
usernameOK = false;
}
else {
$('#usernameCheck').empty();
usernameOK = false;
}
}
});
First of all you should use your console to see Javascript errors, as I'm sure this will generate some. For example that querystring is undefined.
I'd also console.log instead of alert, it is less annoying and more informative.
Then: you dont need to use f.e. ""+marvalue+"" - just use marvalue. On the other hand f.e. queryString should be quoted...
$.post("regsearch.php", {'queryString':value,'queryString1': marvalue,'queryStringfage':fage,'queryStringtage':tage,'queryStringfromh': fromhvalue,'queryStringtoh':tohvalue}, function(data) {
$('#suggestions').fadeIn();
$('#suggestions').html(data);
});

JQuery - Iterating JSON Response

The Story So far....
Trying to learn JS and JQuery and i thought i would start with the basics and try alittle AJAX "search as you type" magic. Firstly i just wanted to get the AJAX part right and iterating through the return JSON object and appending it to a unordered list. Im doing no validation on the inputted value vs. the returned JSON results at this time, i just want a controlled way of when to do the AJAX getJSON call. Later i will do the validation once i get this right.
Anyways im having trouble displaying the Account Numbers in in the ul. At the moment the only thing that is being displayed is AccountNumber in the li and not my ACCOUNT NUMBERS
My JS Code is here:
http://jsfiddle.net/garfbradaz/HBYvq/54/
but for ease its here as well:
$(document).ready(function() {
$("#livesearchinput").keydown(function(key) {
$.ajaxSetup({
cache: false
});
$.getJSON(" /gh/get/response.json//garfbradaz/MvcLiveSearch/tree/master/JSFiddleAjaxReponses/", function(JSONData) {
$('<ul>').attr({
id: "live-list"
}).appendTo('div#livesearchesults');
$.each(JSONData, function(i, item) {
var li = $('<li>').append(i).appendTo('ul#live-list');
//debugger;
});
});
});
});​
My JSON file is hosted on github, but again for ease, here it is:
https://github.com/garfbradaz/MvcLiveSearch/blob/master/JSFiddleAjaxReponses/demo.response.json
{
"AccountNumber": [
1000014,
1015454,
1000013,
1000012,
12
]
}
Also here is my Fiddler results proving my JSON object is being returned.
EDIT:
There were so queries about what i was trying to achieve, so here it goes:
Learn JQuery
To build a "Search as you Type" input box. Firstly i wanted to get the AJAX part right first, then i was going to build an MVC3 (ASP.NET) Application that utilises this functionality, plus tidy up the JQuery code which includes validation for the input vs. the returned JSON.
Cheesos answer below worked for me and the JSFiddle can be found here:
http://jsfiddle.net/garfbradaz/JYdTU/
First, I think keydown is probably the wrong time to do the json call, or at least... it's wrong to do a json call with every keydown. That's too many calls. If I type "hello" in the input box, within about .8 seconds, then there are 5 json requests and responses.
But you could make it so that it retrieves the json only the first time through, using a flag.
Something like this:
$(document).ready(function() {
var $input = $("#livesearchinput"), filled = false;
$.ajaxSetup({ cache: false });
$input.keydown(function(key) {
if (!filled) {
filled = true;
$.getJSON("json101.js", function(JSONData) {
var $ul =
$('<ul>')
.attr({id: "live-list"})
.appendTo('div#livesearchesults');
$.each(JSONData, function(i, item) {
$.each(item, function(j, val) {
$('<li>').append(val).appendTo($ul);
});
});
});
}
});
});
The key thing there is I've used an inner $.each().
The outer $.each() is probably unnecessary. The JSON you receive has exactly one element in the object - "AccountNumber", which is an array. So you don't need to iterate over all the items in the object.
That might look like this:
$.each(JSONData.AccountNumber, function(i, item) {
$('<li>').append(item).appendTo($ul);
});
What you probably want is this:
$.each(JSONData.AccountNumber, function(i, item) {
var li = $('<li>').append(item).appendTo('ul#live-list');
});
Your code:
$.each(JSONData, function(i, item) {
var li = $('<li>').append(i).appendTo('ul#live-list');
});
Says "iterate over the keys and values of the outer JSON structure, and print the keys". The first key is "AccountNumber", so you end up printing that.
What you want to do is iterate over the array stored at JSONData.AccountNumber, and print the values:
$.each(JSONData.AccountNumber, function() {
var li = $('<li>').append(this).appendTo('ul#live-list');
});

ajax - When to use $.ajax(), $('#myForm').ajaxForm, or $('#myForm').submit

Given so much different options to submit sth to the server, I feel a little confused.
Can someone help me to clear the idea when I should use which and why?
1> $.ajax()
2> $('#myForm').ajaxForm
3> ajaxSubmit
4> $('#myForm').submit
Thank you
I personally prefer creating a function such as submitForm(url,data) that way it can be reused.
Javascript:
function submitForm(t_url,t_data) {
$.ajax({
type: 'POST',
url: t_url,
data: t_data,
success: function(data) {
$('#responseArea').html(data);
}
});
}
HTML:
<form action='javascript: submitForm("whatever.php",$("#whatevervalue").val());' method='POST'> etc etc
edit try this then:
$('#yourForm').submit(function() {
var yourValues = {};
$.each($('#yourForm').serializeArray(), function(i, field) {
yourValues[field.name] = field.value;
});
submitForm('whatever.php',yourvalues);
});
Here is my understanding
$.ajax does the nice ajax way to send data to server without whole page reload and refresh. epically you want to refresh the segment on the page. But it has it's own limitation, it doesn't support file upload. so if you don't have any fileupload, this works OK.
$("#form").submit is the javascript way to submit the form and has same behaviour as the input with "submit" type, but you can do some nice js validation check before you submit, which means you can prevent the submit if client validation failed.
ajaxForm and ajaxSubmit basically are same and does the normal way form submit behaviour with some ajax response. The different between these two has been specified on their website, under FAQ section. I just quote it for some lazy people
What is the difference between ajaxForm and ajaxSubmit?
There are two main differences between these methods:
ajaxSubmit submits the form, ajaxForm does not. When you invoke ajaxSubmit it immediately serializes the form data and sends it to the server. When you invoke ajaxForm it adds the necessary event listeners to the form so that it can detect when the form is submitted by the user. When this occurs ajaxSubmit is called for you.
When using ajaxForm the submitted data will include the name and value of the submitting element (or its click coordinates if the submitting element is an image).
A bit late, but here's my contribution. In my experience, $.ajax is the preferred way to send an AJAX call, including forms, to the server. It has a plethora more options. In order to perform the validation which #vincent mentioned, I add a normal submit button to the form, then bind to $(document).on("submit", "#myForm", .... In that, I prevent the default submit action (e.preventDefault() assuming your event is e), do my validation, and then submit.
A simplified version of this would be as follows:
$(document).on("submit", "#login-form", function(e) {
e.preventDefault(); // don't actually submit
// show applicable progress indicators
$("#login-submit-wrapper").addClass("hide");
$("#login-progress-wrapper").removeClass("hide");
// simple validation of username to avoid extra server calls
if (!new RegExp(/^([A-Za-z0-9._-]){2,64}$/).test($("#login-username").val())) {
// if it is invalid, mark the input and revert submit progress bar
markInputInvalid($("#login-username"), "Invalid Username");
$("#login-submit-wrapper").removeClass("hide");
$("#login-progress-wrapper").addClass("hide");
return false;
}
// additional check could go here
// i like FormData as I can submit files using it. However, a standard {} Object would work
var data = new FormData();
data.append("username", $("#login-username").val());
data.append("password", $("#login-password").val()); // just some examples
data.append("captcha", grecaptcha.getResponse());
$.ajax("handler.php", {
data: data,
processData: false, // prevent weird bugs when submitting files with FormData, optional for normal forms
contentType: false,
method: "POST"
}).done(function(response) {
// do something like redirect, display success, etc
}).fail(function(response) {
var data = JSON.parse(response.responseText); // parse server error
switch (data.error_code) { // do something based on that
case 1:
markInputInvalid($("#login-username"), data.message);
return;
break;
case 2:
markInputInvalid($("#login-password"), data.message);
return;
break;
default:
alert(data.message);
return;
break;
}
}).always(function() { // ALWAYS revert the form to old state, fail or success. .always has the benefit of running, even if .fail throws an error itself (bad JSON parse?)
$("#login-submit-wrapper").removeClass("hide");
$("#login-progress-wrapper").addClass("hide");
});
});

Resources