"Autocomplete is not a function" Javascript error - javascript

In my Grails project (version 2.2.1) I'm using the following Javascript code in two different GSP pages.
<g:javascript>
$(document).ready(function() {
$.ajax({
type: "GET",
url: "/medicalOfficeManager/Patient/getAllPatients",
dataType: "json",
success : function(response) {
//Create a map.
var data =
$.map(response, function(item){
console.log("id: " + item.id);
console.log("name: " + item.surname + " "+ item.name);
return{
id: item.id,
value: item.surname + " " + item.name
}
});
$("#patient_textField").autocomplete({
source: data,
select: function (event, ui){
console.log("selected id:" + ui.item.id);
console.log("selected name:" + ui.item.value);
//when a country is selected(ie: type China and press enter),
//change the value of hidden field to the country's id.
$('#patient_id').val(ui.item.id);
console.log("patient value = "+ $('#patient_id').val());
}
});
}
});
});
</g:javascript>
In one GSP everything works as expected, in another one, looking at Javascript console, I have the following error:
$(...).autocomplete is not a function
I've read this discussion, but it does not work for me.
Any suggestion?
EDIT: I've noticed that the only difference betweeen pages is that, in the not working one, it is loaded the bundle-bundle_core_head.js, but I don't see where it is loaded in gsp page...
EDIT2: there was a component loading in other gsp that includes an earlier version of JQuery and JQuery UI, but I need that component because, if I comment it, another field that allows me to choose date and time does not work. Is it possible to use both?

The autocomplete function is likely provided by a jQuery plugin that you are including in one page, but not the other. View the source of each page and compare the <script> elements in each.

Related

Why am I getting a '$' is not defined when running an AJAX query?

Possibly a dumb question, but I have a page where I'm trying to load list data into a customer table to display as a front-end. I'm retrieving this list from a SharePoint list using an AJAX call in a Javascript function, however when I'm using this function my console returns a SCRIPT5009: '$' is not defined error. Previously, I've used an AJAX call successfully using very similar code, but to return a single item from the list using the list ID to search for a specific item, and I've run the query successfully directly from the URL that returns the data I'm after - I'm just not sure what's happening with this one.
function getIncidents(){
$.ajax({
url: "SharepointURL/_api/web/lists/getbytitle('Incident List')/items?$select=Title,Id,Priority,IncidentStart,IncidentStatus,IncidentTitle,UpdateResolution",
type: "GET",
headers: {"accept": "application/json;odata=verbose"},
success: function (data) {
var dResponse = data.d.results;
var results = document.getElementById('Results');
results.innerHTML += "<tr><td>Incident<br>Reference</td><td style='width:20px'></td><td>Priority</td><td style='width:20px;'></td><td>Start Time</td><td style='width:20px'></td><td style='width:170px'>Issue</td><td style='width:20px'></td><td style='width:170px'>Latest Update</td><td style='width:20px'></td></tr>";
for(var obj in dResponse){
results.innerHTML += "<tr style='font-size:10pt'><td>"+dResponse[obj].Title + "</td><td></td><td>" + dResponse[obj].Priority + "</td><td></td><td>" + dResponse[obj].IncidentStart + "</td><td></td><td>" + dResponse[obj].IncidentTitle + "</td><td></td><td>" + dResponse[obj].UpdateResolution + "</td></tr>";
}
}
});
}
Previous example where I have this call working:
function getIncident() {
var listName="Incident List";
var incidentID = $("#incidentReference").val();
if(incidentID!=""){
$.ajax({
url: "SharepointURL/_api/web/lists/getbytitle('Incident List')/items?$filter=Title eq '" + incidentID + "'&$select=Title,Id,SystemOrService,Priority,IncidentStatus,IncidentTitle,UpdateResolution,IncidentStart,ImpactedArea,IncidentEnd",
type: "GET",
headers: {"accept": "application/json;odata=verbose"},
success: function (data) {
if(data.d.results.length>0){
var item=data.d.results[0];
$("#systemImpacted").val(item.SystemOrService);
$("#incidentPriority").val(item.Priority);
$("#incidentState").val(item.IncidentStatus);
$("#incidentTitle").val(item.IncidentTitle);
$("#incidentUpdate").val(item.UpdateResolution);
$("#startTime").val(item.IncidentStart);
$("#impactedAreas").val(item.ImpactedArea.results);
$("#endTime").val(item.IncidentEnd);
updateImpact();
getStartTime();
getEndTime();
actionsFormat();
}
},
error: function (data) {
alert("Incident Reference incorrect or not found");
}
});
}
}
The issue is that jQuery ($) is not yet loaded to the page. If you used it before, this means that loading is already setup, so you don't need to add more references to the jQuery.
In most of the cases, when you working with jQuery, you will subscribe on DOM event ready event and do your code there.
So, all you need is to find the
$(document).ready( ...
statement and insert your code there.
If you want to separate your code from already existed, you may write your own $(document).ready subscription.
If you will not find this $(document).ready function, you can search in html for the reference to the jQuery, and insert your script after it. But, than you need to be sure, that reference doesn't include async or defer attribute.
As mentioned in comments, if you decide to add your own subscription, you also need to place it after jQuery reference, because it will not work, if $ isn't available.

Can I use only one request to fill the same html element?

I'm using ajax to make a request to a webservice.
$(document).ready(function(e) {
var token = "123";
$.ajax({
type: "POST", //REQUEST TYPE
dataType: "json", //RESPONSE TYPE
url: "http://ws/mehtod"+token,
success: function(data) {
console.log(data);
$.each(data, function(i) {
$('#list_countries').append("<option>" + data[i].Name + "</option>"); //fILL THE DDL. FOR EACH ITEM RETURNED ADD DATA[NAME] TO ONE LINE OF THE DDL.-
});
},
error: function(err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
}).always(function(jqXHR, textStatus) {
if (textStatus != "success") {
alert("Error: " + jqXHR.statusText);
}
})
});
and the question is: I have multiple elements in my html that have the ID "list_countries" (they're all the same element but in different panels inside the page) and my rerquest works and treats the data well but for some reason it only fills one of the elements. The others don't fill with the data requested. What can be the cause of this?? Thank you all in advance.
Most likely because you use identificator #list_countries multiple times. Better use class selector or unical ids:
$('#list_countries, #list_countries_2, #list_countries_3');
// or
$('.list_countries');
Try This:
$('#list_countries').each(function() {
$(this).append("<option>" + data[i].Name + "</option>");
});
The selector that you're using tells jQuery to internelly use the native document.getElementById() method for fetching the DOM wich returns ONLY the first node which appears in the page that matches the selector regardless to any other node(s) with the same ID.
So, you have to enforce jQuery to NOT use the native document.getElementById() method and here's a trick for you:
$.each(data, function(i) {
   $('body #list_countries').append("<option>" + data[i].Name + "</option>");
});
Note the body before #list_countries, here we enforce it to use the Sizzle for this job instead of document.getElementById() method.
PS: I strongly suggest that you use the same class for different elements instead of the ID which must be unique in the page.

asp.net mvc bootstrap tab add javascript including partialview automatically

First of all i want to add purchase and sales in same view.And there will be many to one sales or many to one purchases. So i need to call sales model several times in one view with partial view. Then i encountered such a problem.
I have problem with MVC bootstrap tabs. I have one bootstrap tab. In first tab call partialview static like
#Html.Partial("_PurchaseDeal")
But then i add new tabs with add tab button. It is normally adds tabs and load partialview with this code.
<script type="text/javascript">
$(".purchase").on("click", "a", function (e) {
e.preventDefault();
if (!$(this).hasClass('add-purchase')) { debugger
$(this).tab('show');
}
})
.on("click", "span", function () {
$(this).parent().remove();
$(".purchase li").children('a').first().click();
});
$('.add-purchase').click(function (e) {
e.preventDefault();
var id = $(".purchase").children().length; //think about it ;)
var tabId = 'purchase_' + id;
debugger
$(this).closest('li').before('<li>P-'+id+' <span> x </span></li>');
$('.purchasetab').append('<div class="tab-pane" id="' + tabId + '">' + '</div>');
debugger
$.ajax({
url: '#Url.Action("ReturnPurchasePartial", "DEALs")',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'html',
success: function (data) {
debugger
$('#'+tabId).html(data);
},
error:function()
{
alert('Could not save the deal');
}
});
$('.purchase li:nth-child(' + id + ') a').click();
debugger
});
</script>
Now my problem is in first time when i call partial view as a static version javascripts in partialview fires normally.
But when i call partialview inside a javascript code dynamically javascripts in the same partial view are not firing.
Please could anyone can help me to solve this issue?

How to refresh a table inside a div tag using ajax php

I have an ajax table click event that gets database data according to the clicked name from the first table and display the second table with employee information. The problem now is that the employee information data only pile up in the second table, I want to refresh the second table every name that the user clicked. By the way the second table is inside a div tag.
Here is my ajax code:
function putThis(control){
var getid = control.innerText;
var first = $("#from[name=from]").val();
var second = $("#to[name=to]").val();
$.ajax({
type:'POST',
url: 'testtable.php',
data: {id: getid,from: first,to: second},
cache: false,
global: false,
success:function(data)
{
$("#result").append(data);
alert("Success: " + getid + " " + first + " to " + second);
}
});
}
If I am reading your question properly (and correct me if I am not), you want to replace the contents of the element rather than append the data to the element.
This can be accomplished with your code by changing this line :
$("#result").append(data);
To this :
$("#result").html(data);
append will put data at the end of the element before the closing tag, while html will consume the element with the data you are inserting.
In your code as I can see you want to click on user name from left panel and call ajax for his/her information from database .
But as you are appending that information to div and this append call append the data a the end of the div instead you can call $("#result").html(data);.
So final ajax call will be-
$.ajax({
type:'POST',
url: 'testtable.php',
data: {id: getid,from: first,to: second},
cache: false,
global: false,
success:function(data)
{
$("#result").html(data);
alert("Success: " + getid + " " + first + " to " + second);
}
});
if still issue persists you can do following steps -
1. check any error in console tab in firebug.
2. if ajax is failing at any point .

jQuery AutoComplete data from route and using custom data and display

Here is the code I'm attempting to use (parts pulled from remote json, parts removed from the custom data display):
$(function () {
$("#Field1Text").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
url: "/Main/Users/GetItems",
dataType: "json",
data: {
group: "Default",
query: request.term
}
},
focus: function (event, ui) {
$("#Field1Text").val(ui.item.Description);
return false;
},
select: function (event, ui) {
$("#Field1Text").val(ui.item.Description);
return false;
}
})
.data("autocomplete")._renderItem = function (ul, item) {
return $("<li>")
.data("item.autocomplete", item)
.append("<a><strong>" + item.Description + "</strong><br>" + item.Section + " - " + item.Type + " - " + item.Name + "</a>")
.appendTo(ul);
};
});
The data pulls back fine, but the render item function never fires. I've scrapped the render item version and used success: inside of source and it looked like this:
success: function (data) {
response($.map(data, function (ul, item) {
return $("<li>")
.data("item.autocomplete", item)
.append("<a><strong>" + item.Description + "</strong><br>" + item.Section + " - " + item.Type + " - " + item.Name + "</a>")
.appendTo(ul);
}));
}
I used firebug and I was able to hit a breakpoint at the response section: if I looked at the data in data, it looked like:
[ Object { ...data... }, Object { ...data... }]
If I set a breakpoint at the .data line of the success section, I see that ul is one of the objects ( looks like " Object { ... data ... }")
the item element is 0 at this point, and when I attempt to render the <a> tags, it comes out as Undefined on all of the properties (understandable, looks to be treating the item object as an int).
How do I get that component to handle properly?
edit: sorry, I wanted to add a jsFiddle per the suggestion in the comments but had family stuff going on.
http://jsfiddle.net/EYj8v/2/
I commented the code that is similar to what we use at work. Unfortunately, the web app is an internal one with a database that isn't connected to the outside world so I can't use live data. The testResults object is what I saw in the success: section's data element.
I was actually able to get the success section to fire, but I don't believe I'm using jQuery UI/Autocomplete correctly (at least my assumptions) as I was able to look at ul.Properties and see real data. Appending the items worked with bogus data, but when I attempted to copy and paste the success block into the render item, all of the data was undefined. Nor could I find a one-to-one mapping at that stage (ul was the element on the page, item was just [li]).

Categories