Is it possible to call a JavaScript function from within #Html.PagedListPager(in here) ?
I have a button which calls the following function and performs all its supposed to with ease:
function fetchResults() {
$.get('#Url.Action("Search", "Notifications")',
{
device: "Device"
},
function (data) {
$('#results').html(data);
})
};
Now how can I do the same when I click on a page number on my PagedListPager?
Currently my pager reloads the page and that's the main thing I want to avoid.
This is my Pager:
#Html.PagedListPager((IPagedList)ViewBag.NotificationsPage, page =>
Url.Action("Search", "Notifications", new
{
device = "Device",
page = page
}),
PagedListRenderOptions.PageNumbersOnly)
Perhaps there's a much better way to do this. Help will be appreciated.
All that this #Html.PagedListPager helper does is spit some HTML containing links to perform the pagination. So you could subscribe to the click event of those links and AJAXify them:
$(document).on('click', 'a', function() {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
success: function(result) {
$('#results').html(result);
}
});
return false;
});
Important things to note:
I have subscribed to the click event in a lively manner. This means that if we replace the links in the success callback of the AJAX request, this click event handler will continue to work
You might want to adjust the $(document).on('click', 'a', function() { selector which is pretty inclusive and target only the links generated by this pager. For example look if they are not inside some containing div or something in which case you could use something along the lines of $('.pager').on('click', 'a', function() {.
Inside the success callback you might need to adapt the $('#results') selector to target the div containing the actual results which will get refreshed with the partial HTML returned by your controller action.
Talking about partial HTML and controller action you will obviously need to adapt the controller action that gets invoked in the AJAX request to return a PartialView instead of a full View containing only the updated records and new pagination links.
Related
I am working on a jquery/ajax project. On document ready, I have the following code:
$(document).ready(function () {
$.ajax({
url: '/Main/ReturnGroups/',
dataType: "json",
success: function (data) {
$('.column').each(function (index) {
let indexVar = index;
let colID = $(this).attr("id");
for (let i = 0; i < data.length; i++) {
if ($(this).attr("id") == data[i].ColumnID) {
let thisID = $(this).attr("id");
let thisGroupID = data[i].ID;
$.ajax({
url: '/Main/GetFullGroup/',
data: { groupID: thisGroupID },
success: function (html) {
$('#' + thisID).append(html); //this html inserts a portlet (JqueryUI) based element
}
});
}
}
})
},
complete: function () {
alert($('.portlet').length); //returns 0 (leads me to believe its being run before success function
AddPageProperties(); //this function is supposed to add a bunch of classes to the elements injected in the success function but doesnt actually add the classes when its here
}
});
})
It seems to me that the contents of the complete: function is running asynchronously with the success function. From my understanding the purpose of the complete function is to run once the ajax success (or error) function is completely done.
The code is iterating all the columns and returning all the groups which have the same column id in my database, then passing the groupID to another webmethod which is then querying for all tasks and using the passed in groupID only pulling the tasks that are associated to the group, then using that data to inject a partial view to place the tasks/groups in their respective locations.
Things I've tried:
-Put the AddPageProperties() function in a button click, and after the ajax is finished, click the button. This works exactly as intended.
-use ajaxStop(). While this does work as I want for document ready, once I submit another ajax request it runs the function again, thus duplicating the code. My project uses ajax requests when elements are moved around the screen so this doesnt work.
-Try and get the details of an element to see if the html is even there in the first place when the complete: function() is run. The alert in the code snippet returns 0, which leads me to believe the HTML is not there when that alert is executed.
-using the index of the each function to determine the end of the iteration and then run the function, but again does not apply classes in the function. I tried to again do an alert to see if the elements are present, but they are not.
-set async to false, but the browser just says that its deprecated and it doesnt change any behavior
Any advice on the path towards a solution is appreciated. My goal is once all the HTML is injected, then and only then run this function and never again until page is reloaded sometime later.
I would like to stick with JQuery/ajax as my project is dependent on JQuery for Bootstrap.
I have a VIEW, which contains a dataTable and jquery code which enables the dataTable rows to be clickable so that the user can click on a row and an ajax call is made to the server to fetch the detail of that row.
I've manage to make the dataTable row clickable, and called the Ajax function which under debug mode, I can see the POST method is being called. However, the Partial View which the returned by the POST method does not show up on my browser, even though I can see that my code is being called every step in debug mode..
My ajax/jquery is this (ive got this in a VIEW)
<script type="text/javascript">
$(function () {
$('#dTable tbody tr').on('hover', function () {
$(this).toggleClass('clickable');
}).on('click', function () {
var self = this;
$.ajax(
{
type: "POST",
url: "/TR/AllTHeaderTR",
data: { tID: $.trim($(this).find('td:first').text()) },
success: function (data) {
$('#dtable').html(data);
$(self).off('click');
}
});
});
</script>
I can see that when clicked, the code does move through the POST method, /TR/AllTHeaderTR, which ends up doing a : return PartialView("_AllTDetailTR", travlist);
Ive also tried to replace the above with just a normal HTML page with hard coded text, but the page does not render.
Im not clued up on jquery or ajax, so could someone please assist.
Thanks
Naren
I have a page view that makes an ajax call and updates the contents of the page with renderPartial.
So page.php -> _pagePartial.php (ajax update)
in page.php I want to include the javascript files once, then have the DOM modifications apply after the ajax rendering happens. It doesn't make sense to have this JS file load on every AJAX refresh.
For example in page.php
$baseUrl = Yii::app()->baseUrl;
$basePath = Yii::app()->basePath;
$cs = Yii::app()->getClientScript();
$cs->registerScriptFile($baseUrl . '/js/jquery.ui.js'); // load one time!
then in pagePartial.php
// every ajax partial load
$('#sortable-list-left').sortable({
connectWith:'.productEntryCol',
placeholder: 'ui-state-highlight',
update: function(event, ui) {
var sortOrderLeft = getSortOrder('sortable-list-left');
var sortOrderRight = getSortOrder('sortable-list-right');
var projectId = '" . $project_id . "';
$.ajax({
data: { left: sortOrderLeft, right : sortOrderRight, id : projectId},
url: '/project/ajaxUpdateOrder',
type: 'POST',
success: function(response){
// process JSON response
var obj = jQuery.parseJSON(response);
}
});
}
});
The problem is after _pagePartial loads via AJAX, it can't use the .sortable() method.
What is the proper way to handle this ?
Thanks
The way I handle this is on the main view on the $.load or $.ajax or whatever it is, add your code on the success function.
So for example:
$.get('_pagePartial.php', null, function(html) {
$('#result').html(html);
$('#sortable-list-left').sortable({
//all your sortable code
});
});
Another option is to add your javascript on your ajax loaded page ('_pagePartial.php') into a function like so:
function firejs() {
$('#sortable-list-left').sortable({
//all your sortable code
});
}
Then on your successful ajax call on your main view ('page.php') simply add this:
$.get('_pagePartial.php', null, function(html) {
$('#result').html(html);
firejs();
});
You can bind to an object until it is added to the DOM and it isn't added to the DOM until the ajax call has finished successfully and the result is added to the DOM.
Also just an FYI yii has jqueryui built in you can simply say:
Yii::app()->clientScript->registerCoreScript('jquery.ui');
Yii::app()->clientScript->registerCoreScript('jquery');
For people like me who has the same issue, even with:
Yii::app()->clientscript->scriptMap['jquery.js'] = false;
in the renderPartial and still not work. I've found another solution, way more effective I think. The easiest solution is to set the 4th parameter of renderPartial.
RenderPartial-detail
public string renderPartial(string $view, array $data=NULL, boolean $return=false, boolean $processOutput=false)
It is about processOutput.If you put it to true, then Jquery will be loaded in your render Partial.
Hope this will help someone...
$(function(){
$(".mailbutton").click(function() {
var email = $(".mailingfield").val();
$.post("/PHP_scripts/mailinglist.php", { email: email }, function(data) {
var content = $(data).find("#mailinglistform");
$("#box").empty().append(content);
});
});
});
I'm using this to process an email address. If it fails in the PHP script the form is sent back in the '.mailinglistform' with a fresh form and some text explaining the error. The problem I have is that even though the button has the '.mailbutton' class in the callback form, the button doesn't do anything on click.
Is this because the jQuery only recognises it first time round? If so, is there a way to "reload" the 'mailbutton' .click function on callback?
Thanks!
You're right that because you're only re-rendering a portion of the page, the previous jQuery you wrote does not register with the "new" mailbutton class that you've re-rendered. To get around this, you should use .on(), e.g.:
$(".wrapper").on('click', '.mailbutton', function() {
var email = $(".mailingfield").val();
$.post("/PHP_scripts/mailinglist.php", { email: email }, function(data) {
var content = $(data).find("#mailinglistform");
$("#box").empty().append(content);
});
});
In this case, wrapper needs to be a class element that's outside of the re-rendered section (e.g. the 'content' class, maybe a class around your form, etc) of the page, and one that is constantly present (i.e. not re-rendered in the ajax call). This will attach an onclick handler to any .mailbutton classes that are children of the wrapper class, whether they are present when the page is rendered, or if they are added to the DOM later.
Use on to bind click event. When control is render again in the callback function its events are removed. Using on instead of click could rebind the events automatically.
$(function(){
$(".mailbutton").on("click", function() {
var email = $(".mailingfield").val();
$.post("/PHP_scripts/mailinglist.php", { email: email }, function(data) {
var content = $(data).find("#mailinglistform");
$("#box").empty().append(content);
});
});
});
For this you can use AJAX with JQuery. OR you can alos user load().
$(".mailbutton").click(function() {
$.ajax({
url: 'api.php', // Put your calling page path here
data: "",
dataType: 'json',
success: function(data)
{
//do whatever you want to do on success
}
});
});
I have a bunch of portfolio items sorted as tabs on this page. Link to the site. The site is built with Joomla 2.5 and I have a component that takes care of displaying each portfolio item.
What I need to do is to load each respective portfolio item without reloading the page. So basically here is the javascript function that has the AJAX call
function ajax_portfolio($pid) {
var url = 'index.php?option=com_jms_portfolio&task=item.ajax_load_portfolio&tmpl=component&id=' + $pid;
alert(url);
var x = new Request({
url: url,
method: 'post',
evalScripts: true,
evalResponse: true,
onSuccess: function(responseText){
document.getElementById('ja-content-main').innerHTML = responseText;
aaa();
}
}).send();}
The issue in fact is not the AJAX call cause and the click event of tag, there is no problem with this event. The problem is to fire the javascript function aaaa() after each ajax call. Sorry if I was not clear but the problem is to fire the function aaa() after each ajax call, this function creates the slider for each portfolio item.
Remove the existing href attribute of the <a> tags that wrap the images. Then, add the a click handler through javascript to each <a> tag after giving them a unqiue id. This will then cause the ajax to be called when clicking on the images instead of redirecting to a new page.
As for calling the aaa function, I assume the issue is scope since you have not posted the method. To give aaa the correct scope, you can pass an extra parameter to ajax_portfolio to acomplish this.
A JQuery example follows.
<a port_id="56"><img>...</img></a>
$(document).ready(function() {
$("a").click(function() {
ajax_portfolio($(this).attr("port_id"), $(this));
});
});
// Add the $elem parameter here to track which element called this method.
function ajax_portfolio($pid, $elem) {
var url = ...;
var x = new Request({
url: url,
method: 'post',
evalScripts: true,
evalResponse: true,
onSuccess: function(responseText){
document.getElementById('ja-content-main').innerHTML = responseText;
// Pass the element that was clicked on to the aaa function.
aaa($elem);
}
}).send();}