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.
Related
I got a html page #main that is fully loaded by a javascript function loadNe(). After the page gets fully loaded by the Ajax call, I want some tooltips to be shown when mouseovering some rows. Those tooltips makes Ajax requests to exhibit its content. The problem is:
The "open:" function inside tooltip() is probably never being executed because nothing gets printed in the console by the console.log() inside it. And also no network requests are sent to the tooltip's ajax URL. But still, the tooltip is working when I mouseover the elements, it shows me the title's tag content "Loading...".
What can be going wrong here?
function loadNe(ne){
$.ajax({
type: "GET",
url: "/NOKIA/fx-load.php?label=" + ne,
dataType: "text",
success: function (data){
var content = fillResult(data);
$("#main").html(content).hide();
$("#main").fadeIn("slow");
$(".sfp").tooltip({
track: true,
open: function (event, ui){
var sfp = $(this).text();
console.log("1-executing.."+sfp);
$.ajax({
type: "GET",
url: "/NOKIA/sfp-load.php?sfp="+sfp,
dataType: "json",
success: function(data){
console.log("2-executing.."+data["reach"]);
var html = "<tr><td>Alance: "+data["reach"]+"</td></tr>"+
"<tr><td>Tamanho de onda: "+data["wavelength"]+"</td></tr>"+
"<tr><td>Limiar Rx: "+data["rx_min"]+"</td></tr>";
$(".sfp").tooltip('option','content',html);
}
});
}
});
}
});
}
The problem was I was loading the bootstrap.min.js before the js-ui.min.js. The tooltip() function was executing the bootstrap library instead of the js-ui. So I inverted the order of loading as it is down here:
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="js-ui/jquery-ui.min.js"></script>
I have some JS files included in my page that are simple for displaying blocks on click ant etc..
On another part of page, I have a button. When I click it an ajax call is made that returns some values that I display on the page. To display it, I'm reloading part of page like this:
$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
}
}
});
});
This reloads part of page, displays values and etc..
However, after the ajax call is made, the JS stops working. When I click my buttons, nothing happens. No errors or anything.
I think it has to do with the ajax when I refresh part of twig and it messes up the previously loaded JS files. But what can I do in that situation? Somehow refresh the loaded JS files? How?
You have to attach event listener on button starting from the container which doesn't get reloaded by Ajax request, like this:
//#mainCont is a container that doesn't get reloaded by Ajax
$("#mainCont").on("click", ".yourBtn", function(){
//do something
});
As said #Nacho M, you need to reinit listener from the loaded element, so you hsould have something like this :
function init() {
$(document).on('click', '.yourclass', function (e) {
//your content
}
// add every button who needs to be reloaded.
}
Init them on loading page first :
$("document").ready(function() {
init();
})
And on success of Ajax call :
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
init();
}
}
});
I have php page "Home.php", that present user posts(using ajax).
This is how I get the posts:
<script type="text/javascript">
function loadmore()
{
var val = document.getElementById("result_no").value;
var userval = document.getElementById("user_id").value;
$.ajax({
type: 'post',
url: 'fetch.php',
data: {
getresult:val,
getuserid:userval
},
success: function (response) {
var content = document.getElementById("result_para");
content.innerHTML = content.innerHTML+response;
// We increase the value by 2 because we limit the results by 2
document.getElementById("result_no").value = Number(val)+10;
}
});
}
</script>
<div id="content">
<div id="result_para">
</div>
</div>
In every post, there is a like button(which also uses ajax). This is how I save the likes:
<script type="text/javascript">
function likethis(likepostid)
{
$.ajax({
type: 'post',
url: 'fetchlikes.php',
data: {
getpostid:likepostid
},
success: function (response) {
}
});
}
</script>
Before I used ajax to present posts, all worked well. But now when I press the like button, it DOES save the like, BUT the javascript/jquery doesn't work. I tried to make alert when I pressed the LIKE button, but it didn't work.
This is the index.js code(the javascript). It add +1 likes, when the user press the button:
$('.btn-counter_likecount').on('click', function(event, count) {
event.preventDefault();
//alert("hello");
var $this = $(this),
count = $this.attr('data-count'),
active = $this.hasClass('active'),
multiple = $this.hasClass('multiple-count_likecount');
$.fn.noop = $.noop;
$this.attr('data-count', ! active || multiple ? ++count : --count )[multiple ? 'noop' : 'toggleClass']('active');
});
EDIT fetchlikes.php:
<?php
mysql_connect('localhost','root','');
mysql_select_db('blabla');
$postid=$_POST['getpostid'];
mysql_query("UPDATE user_post SET likes_count=likes_count+1 WHERE post_id='$postid'");
?>
Because your posts are being loaded dynamically, the javascript where you bind the event is running before the posts are actually loaded, thus the buttons don't exist when you try to bind the event. You can use delegated events in jQuery to handle this.
Your previous code
$('.btn-counter_likecount').on('click', function(event, count) {
....
});
New Code
$('#result-para').on('click','.btn-counter_likecount',function(event, count) {
....
}
This way the event will actually be bound to a parent element that already exists when jQuery's ready() function runs. This way, the event handler checks for matching elements when the event is fired rather than when the event is bound.
For further reading, look into jQuery's delegated events
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)
I have a simple jQuery function that resizes text areas, and I want it to apply to all text areas.
For the most part, this works great:
$(document.ready(function(){$("text_area").resizer('250px')});
However, because it is only called once when the document is ready, it fails to catch text areas that are later added onto the page using Ajax. I looked at the .live() function, which seems very close to what I'm looking. However, .live() must be bound to a specific event, whereas I just need this to fire once when they're done loading (the onLoad event doesn't work for individual elements).
The only thing I can get working is a really obtrusive inclusion of the JavaScript call directly into the Ajax. Is that the recommended way to be doing this?
Edit: Here is the rails source code for what it does for Ajax requests:
$('a[data-confirm], a[data-method], a[data-remote]').live('click.rails', function(e) {
var link = $(this);
if (!allowAction(link)) return false;
if (link.attr('data-remote') != undefined) {
handleRemote(link);
return false;
} else if (link.attr('data-method')) {
handleMethod(link);
return false;
}
});
// Submits "remote" forms and links with ajax
function handleRemote(element) {
var method, url, data,
dataType = element.attr('data-type') || ($.ajaxSettings && $.ajaxSettings.dataType);
if (element.is('form')) {
method = element.attr('method');
url = element.attr('action');
data = element.serializeArray();
// memoized value from clicked submit button
var button = element.data('ujs:submit-button');
if (button) {
data.push(button);
element.data('ujs:submit-button', null);
}
} else {
method = element.attr('data-method');
url = element.attr('href');
data = null;
}
$.ajax({
url: url, type: method || 'GET', data: data, dataType: dataType,
// stopping the "ajax:beforeSend" event will cancel the ajax request
beforeSend: function(xhr, settings) {
if (settings.dataType === undefined) {
xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script);
}
return fire(element, 'ajax:beforeSend', [xhr, settings]);
},
success: function(data, status, xhr) {
element.trigger('ajax:success', [data, status, xhr]);
},
complete: function(xhr, status) {
element.trigger('ajax:complete', [xhr, status]);
},
error: function(xhr, status, error) {
element.trigger('ajax:error', [xhr, status, error]);
}
});
}
So in my particular case, I've got a link, that has data-remote set to true, which points to a location that will return JavaScript instructing a form containing a text area to be appended to my document.
A simple way to do this would be to use ajaxComplete, which is fired after every AJAX request:
$(document).ajaxComplete(function() {
$('textarea:not(.processed)').resizer('250px');
});
That says "every time an AJAX request completes, find all textarea elements that don't have the processed class (which seems to be added by the resizer plugin -- terrible name for its purpose!) and call the resizer plugin on them.
You may be able to optimise this further if we could see your AJAX call.
Generally speaking, I would do it this way..
$.ajax({
type : "GET",
url : "/loadstuff",
success: function(responseHtml) {
var div = $("#containerDiv").append(responseHtml);
$("textarea", div).resizer("250px");
}
});
Wondering if you could use .load for this. For example:
$('text_area').load(function() {
$("text_area").resizer('250px');
});