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
Related
I have a normal button, which triggers a basic function that prints the value of an element in my HTML to the console.
Now, instead of printing the value of that element i want to send it to my Django view with a POST request.
Here is the function:
$(document).on('click','.btnClick', function() {
var myvalue = $(this).data("myid");
console.log(myvalue);
});
Here, instead of printing that value, i want to send myvalue with a post request using Ajax.
I know how to do a POST request, the only difference is that this time, instead of using a form, i'm using a single button to trigger the request, and i'm not really used to that.
Here is how i would do it with a form:
$(document).ready(function () {
$("#myform").submit(function (event) {
$.ajax({
type: "POST",
url: "/myurl/",
data: {
'myvalue': $('id').val()
},
});
return false;
});
});
So, basically i just need to know how to integrate this piece of code inside the first function, so that the Ajax call is triggered not by the form (as it is in the second code) but from a button.
Just put your jquery ajax function inside into the click event function.
$(document).on('click','.btnClick', function() {
var myvalue = $(this).data("myid");
$.ajax({
type: "POST",
url: "/myurl/",
data: {
'myvalue': myvalue
},
});
});
Hope this will help.
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 am using ASP.Net MVC and jQuery 1.8.2
I have a form with a button that calls this javascript when it is clicked:
$(function () {
$('#SearchButton').click(function () {
var data = $('#FilterDefinition :input').serialize() + "&PageNumber=1";
$.post('#Url.Action("Search")', data, LoadContentCallback);
$("#SearchResults").show();
});
});
This calls an MVC Controller Action which returns a PartialViewResult
On the Layout page I have the following JavaScript code:
//Add a custom header to all AJAX Requests
$(document).ready(function () {
$.ajaxSetup({
beforeSend: function(xhr) {
debugger;
if ($('[name=__RequestVerificationToken]').length) {
var token = $('[name=__RequestVerificationToken]').val();
xhr.setRequestHeader('__RequestVerificationToken', token);
}
}
});
});
When the button is clicked for the first time, the beforeSend function is called correctly. However, if the button is clicked more than once (for example they change the search criteria and search again) then the beforeSend function never gets called again and the validate anti-forgery fails.
I tried using the ajaxSend event instead and I got the same results.
Any help is solving this problem would be greatly appreciated.
Thanks!
It turns out the problem was that the partial view that was being rendered was referencing a different version of jQuery. I removed this reference and everything started working correctly.
Thanks!
I would avoid using $.ajaxSetup if possible. I would just setup your beforeSend in the actual POST request.
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.
I am using jquery tabs and trying to use the onclick function but it seems it is not firing. When user clicks the tab and i want to change the detailview mode into readonly mode. Here is my code in aspx:
<div id="tabs-2" class="column" onclick="ChangeMode">
and here code behind:
protected void ChangeMode()
{
if (DV_Test.CurrentMode == DetailsViewMode.Insert)
{
DV_Test.ChangeMode(DetailsViewMode.ReadOnly);
LoadDet();
}
}
I am using this code that forces the pageto stay the selected tab when post pack occurs and it works fine.
<script type="text/javascript">
var selected_tab = 1;
$(function () {
var tabs = $("#tabs").tabs({
select: function (e, i) {
selected_tab = i.index;
}
});
selected_tab = $("[id$=selected_tab]").val() != "" ? parseInt($("[id$=selected_tab]").val()) : 0;
tabs.tabs('select', selected_tab);
$("form").submit(function () {
$("[id$=selected_tab]").val(selected_tab);
});
});
I'm assuming you're using ASP.NET C# because of your tags and syntax. I can suggest these options: use Razor view, or use the JavaScript/jQuery you're already using.
If you prefer to use the Razor View, take a look at the references in this question and use the # symbol to call server functions. In this case, #ChangeMode is what you're looking for.
Since you're using jQuery already I suggest you write a JavaScript function using jQuery .click(). Since the JavaScript and jQuery are both able to call the server, you will be able to access your server-side function ChangeMode.
$('#tabs-2').click(function(){
//Make call to server here. You can use [Ajax][4],
//or see the link below concerning ASP.NET C#
});
link, see this fiddle
Ajax calls:
I've found the jQuery .ajax() call very useful, and this is what my .ajax() calls usually look like:
//get information from server and inject in my div with id="mydiv"
$.ajax({
url: '/ControllerName/MethodName',
type: 'POST',
data: ko.toJSON({myvariable}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#mydiv').html('visiblity', 'visible');
},
error: function (error) {
alert('Cannot retrieve data');
}
});
Also, I'm not sure what you've decided on using, but I liked these suggestions for tabs: try the html found here, which uses ul/li and a to make the tabs themselves. The thing that triggers the action is typically the a.