I've got a view to create Project models which contains (among other things) a table of company-related data.
I've added a button that does an AJAX call to retrieve a partial view and adds it to the table:
$("#addCompanyRoleProject").click(function () {
cache: false,
$.get('CompanyRoleProjectEntryRow', function (result) {
$("#companyTable").append(result); // Add the row to the table
}, "html").done(function (result) {
});
return false;
});
The partial view is a < tr > in wich one of the < td >'s has an input field:
<input class="company-role-project-company" type="text" data-containerPrefix="#ViewData["ContainerPrefix"]" />
I want that input field inside the partial view received by ajax to be an autocomplete (http://jqueryui.com/autocomplete/) so that the user is able to select from a set of options on each < input > for each row of the table.
I can't seem to access the correspondent field on my AJAX call inside the main view. I've tried using "filter()" and "find()" on both the success and done functions.
I could put my javascript code inside the partial view, but it would then be replicated, not to mention possible ID colisions =\
Any ideias on how to achieve this?
EDIT:
I believe I have everything properly referenced in my view:
#section Scripts {
#Styles.Render("~/Content/themes/base/css")
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
<<<< My JS code is here >>>>
}
And in my page's source code I can see:
<script src="/Scripts/jquery-1.7.1.js"></script>
<script src="/Scripts/jquery-ui-1.8.20.js"></script>
<script src="/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
EDIT 2:
I followed Darin Dimitrov's advice and added this on the ajax success callback, after appending the result to the table:
$('input.company-role-project-company', result).autocomplete({
...define source etc...
});
But when I type something in the input field, it behaves like a regular text field...
Is there something wrong in my process of using an ajax call to: request a partial view, append it to the table, make it an autocomplete ?
Try like this inside your AJAX success callback after you append the new partial markup to the DOM:
$('input.company-role-project-company', result).autocomplete({
...
});
I ended up doing it like this:
// Add entry to table
$(function () {
$("#addItemButton").click(function () {
cache: false
$.get('URL.......', function (template) {
$('#table> tbody:last').append(template);
});
return false;
});
});
$(".the-class-used-in-the-desired-field-from-partial-view").live("click", function () {
$(this).autocomplete({
source: function (request, response) {
$.ajax({
url: "URL.........", type: "GET", dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { ....... };
}))
}
})
},
minLength: 1,
select: function (event, ui) {
... Do some magic ...
}
});
});
I.E., I bound the autocomplete with a .live function, outside the AJAX.
Probably not the best way, but so far it's working as I want it to, for multiple entries.
Thanks to Darin Dimitrov anyway for pointing me to the right direction with the
$('input.company-role-project-company', result)
Related
I have problem getting a jquery executed in my parial view which loaded dynamically.
Parial View
<input type="text" id="producerSearch" select-box-search-performer="true" select-box-search-url="TestUrl" select-box-search-performertype="Producer" select-box-search-destination="#Destination")" />
Jquery
<script>
$(document).ajaxSuccess(function() {
$(":input[select-box-search-performer]").each(function () {
var $element = $(this);
$(this).autocomplete({
source: function (request) {
var url = $element.attr("select-box-search-url");
var destSelect = $element.attr("select-box-search-destination");
var performertype = $element.attr("select-box-search-performertype");
$.ajax({
async: false,
cache: false,
type: "POST",
url: url,
data: { "term": request.term, "productId": #Model.ProductModel.ProductId, "performerType": performertype},
success: function (data) {
$(destSelect).empty();
for (var i = 0; i < data.length ; i++) {
$(destSelect).
append($("<option></option>").attr("value", data[i].ID).text(data[i].Name));
}
}
});
}
});
});
});
</script>
Some of the discussions say "ajaxSuccess need to be included (as the code above). However this does not fire the jquery on dynamically loaded partial view.
-Alan-
Well I think since you have a partial view, which is loaded dynamically. And since dynamic content loading is an ajax business, so whenever you load the dynamic view firstly the content is loaded and secondly the ajaxsuccess is triggered, so $(":input[select-box-search-performer]").each(function) works and that time, and not before that.
What you need to do is that you should check the logic which renders dynamic view, and trigger a callback from there when partial view has rendered, and then execute this code.
I have a button that adds an input box where you can type an address. For the address, I'm using the geocomplete plugin. In all input boxes that were not generated with ajax the geocomplete works. If the input was generated by ajax, it doesnt.
This is my code to generate the input box:
$('.add-drop').on('click', function(){
$.ajax({
url : '/ajax/get-location-input',
success : function(data){
$('#additional-drop').append(data);
}
});
});
This is my geocomplete code:
$(".get-location").geocomplete({
details : "form",
types : ["geocode", "establishment"]
}).bind("geocode:result", function(event, result){
console.log(result);
});
The problem is not with the class. I was trying to do something like $(".get-location").on("geocomplete"... but it wasn't working. Any idea? Thanks
AJAX is Asynchronous (Asynchronous JavaScript and XML) That means it might execute after the main code has been finished processing
$.ajax({
url: '/ajax/get-location-input',
success:function(data){
alert(data);
}
});
alert('Hi ');
In this case, Hi will alert first, then data. In your case, the inputs might not even be generated yet and so the geolocation code won't see them
The correct code:
$.ajax({
url: '$('#additional-drop').append(data);',
success:function(data){
$('#additional-drop').append(data);
$(".get-location").geocomplete({
details: "form",
types: ["geocode", "establishment"]
});
}
});
Will make the code run after the data has been fetched from the server
This is me recommended way to do this:
(function () {
$.fn.addGeolocation = function () { this.geocomplete({ details: "form", types: ["geocode", "establishment"] }).bind("geocode:result", function(e, a){ console.log(a); }); }
$.get('/ajax/get-location-input', function (a) {
$('#additional-drop').append(data);
$(".get-location").addGeolocation();
});
/* You may or may not need this */
window.onload = function () { $(".get-location").addGeolocation(); }
}());
My page makes an Ajax call which returns some HTML to embed in the page and a script to run, attaching JQuery tooltips to various elements of the embedded HTML. The HTML and script are returned as JSON objects by my Django backend, and appear OK in the page, but the Javascript doesn't seem to work when I evaluate it:
$.ajax({
type: "GET",
url: "/url/to/ajax",
data: {
"foo": bar
},
success: function (data) {
$("#my-table").html(data['html']);
// alert(data['script']); // this works: I can see the script
eval(data['script']);
},
error: function () {
$("#my-table").html('');
}
});
The script itself looks like a series of expressions such as:
$(".foobar1").tooltip({
content: "The <em>foo</em> to the <strong>bar</strong>.",
tooltipClass: "tt-ref",
show: null,
close: function (event, ui) {
ui.tooltip.hover(
function () {
$(this).stop(true).fadeTo(400, 1);
},
function () {
$(this).fadeOut("400", function () {
$(this).remove();
})
});
}
});
where foobar1 is a class in the HTML just added to the #my-table HTML.
Can anyone see where I'm going wrong here? Both jquery and jquery-ui are loaded on my page.
You don't need to eval anything, let browser execute it. For this create script element, set its content and append it to DOM:
success: function(data) {
$("#my-table").html(data.html);
$('<script>').html(data.script).appendTo('body');
},
Another, probably better option is to make script a part of the returned HTML.
You might try :
eval("data['script']");
I have the follwoing JQuery/AJAX code:
<script>
$('.warning-dialog').click(function () {
alert($(this).data("id"));
});
$(function () {
//twitter bootstrap script
$("button#delete").click(function () {
$.ajax({
type: "GET",
url: "deleteArticleType.php",
data: { 'typeID': $('.warning-dialog').data("id") },
success: function (msg) {
$("#thanks").html(msg)
$("#form-content").modal('hide');
},
error: function () {
alert("failure");
}
});
});
});
</script>
The first function gets the data-id of a button . The second function calls a PHP page and with the method GET should get the value from the first function.
I tried the code above but it didn't work.
My question is why and how can I fix it?
If these are two separate events, disconnected in time and you want to store the value from the first click and then use it in the second click, then you will have to store it somewhere. There are several options, the simplest being a variable.
$(function () {
var lastClickId;
$('.warning-dialog').click(function () {
lastClickId = $(this).data("id");
});
//twitter bootstrap script
// FIXME: you need to add logic here for what to do if lastClickId isn't set yet
// or create a default behavior in that case
$("button#delete").click(function () {
$.ajax({
type: "GET",
url: "deleteArticleType.php",
data: { 'typeID': lastClickId },
success: function (msg) {
$("#thanks").html(msg)
$("#form-content").modal('hide');
},
error: function () {
alert("failure");
}
});
});
});
Since it looks like you are requiring the first click to happen before the second click can have something to operate on, then you should probably either modify the UI to use different types of controls or you will need to add some error handling if the user doesn't click in the right order.
Actually it should have worked using $('.warning-dialog').data("id")
If your page contains only a single class warning-dialog, you approach will be worked. It seems you're referring this class to many elements.
I have two separate AJAX calls. One that gets a list of items from a txt file and creates an HTML table out of them and one that talks to a database to find how much each item costs and then lists this in the corresponding table cell for each item (I know this may sound like a strange approach, but it's a good option in our case...).
The issue is that the price is not getting written to the table since the table is created (or to be precise, the rows of the table are created) after the page loads. I'm not sure how to fix this.
$(document).ready(function() {
makeItemTable();
listPrices();
...
});
function makeItemTable() {
$.ajax({
url: 'products.php',
type: 'GET'
})
.done(function(response) {
$('.price-table > tbody').html(response);
})
}
function listPrices() {
.ajax({
url: 'prices.php',
type: 'GET'
})
.done(function(response) {
priceData = $.parseJSON(response);
$('.price-table tr').each(function() {
var item = $(this).find('td:nth-child(1)').text();
if (priceData[item]) {
var price = priceData[item];
$(this).find('td:nth-child(2)').text(price);
}
})
}
You can try
Using setTimeout to check request to 'products.php' execute callback done (inside callback for request to 'prices.php')
Another way
var jqxhr1 = $.ajax("products.php");
var jqxhr2 = $.ajax("prices.php");
$.when(jqxhr1, jqxhr2).done(function(jqxhr1, jqxhr2) {
// Handle both XHR objects
alert("all complete");
});
Call function listPrices() inside callback request to 'products.php'
Hope to help