ajaxSetup beforeSend only being called the first time button is clicked - javascript

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.

Related

Ajax call after page load

I am trying to build a search page where the user inputs text into a search box and the page is generated based on the search. I am having timing issues because the blank search page is loading after the JS tries to edit the values on the page.
$.ajax({
type: 'GET',
url: '/index.php/content/generate_search',
data: {
search: input.val()
},
beforeSend: function() {
window.location.href = '/index.php/content/search';
},
success: function() {
$('.hero h1').text(input.val());
}
});
To check that the DOM is completely loaded, many steps have to be done taking all the browsers into consideration. (I cannot find the implementation in the jQuery source, but I will come back with a link).
The easiest and probably best way of doing it, since you're already using jQuery is by:
$( function() {
// your code here
} );
which is a shorthand for
$( document ).ready( function() {
// your code here
} );
EDIT
Ok, so as I promised, I came back with the implementation of document.ready. You can find it here, on GitHub. Here is a permanent link to the current version of the file.
Try this:
$(document).ready(function(){
//Your code
});
onload is used for executing code on pageload
window.onload = function() {
// your code
};
This code:
beforeSend: function() {
window.location.href = "/index.php/content/search";
},
… is causing the browser to leave the page and load a new one before it sends the Ajax request.
Consequently, the Ajax request gets cancelled. If it didn't, then there would be no JavaScript waiting to receive the response.
If you want to visit /index.php/content/search and then initiate an Ajax request, then the JavaScript to initiate the Ajax request has to be on /index.php/content/search. A page you've just left can't run JavaScript on the next page.

Ajax post method not returning Partial View

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

How to get the id of a dynamically created form in jquery

I am using a Bootstrap modal to display an ASP.Net MVC5 form, the form is inserted dynamically into a div using a jquery ajax call to the relevant controller and then opened.
I need to intercept the submission of the form so I would like to bind to the submit event of the form in jquery but have so far only been able to bind to the submit event of all forms since the dynamic forms are of course not present when the main view is rendered e.g.
$('form').submit(...)
rather than
$('#serverForm').submit(...)
Whilst this sort of works, it has a problem in that I actually have 3 different dynamic forms in this view which can be shown using modal popups, thus I need to do one of 2 things:
A) (ideally)manage to intercept the submit event for each form.
B) in the global form event handler, identify which form has been submitted.
I have tried every option I can imagine to use option A including adding the binding to the code which pops the modal. all without success.
I am currently trying to go with option B so that I can then decide where to post the form. This does at least get called when a form is submitted but my problem is that I cannot get the id or name of the form which has been submitted and thus have no way of knowing which one it is.
I have the following handler:
<script>
$(function () {
$('form').submit(function(e) {
// this is always null
var id = $(this).attr('id');
$.ajax({
url: '#Url.Action("EditServer", "AccountAdmin")',
data: new FormData(this),
...
});
});
});
</script>
Within this handler I have tried the following (plus a few more!) to get the form's id:
this.id
$(this).id
$(this).attr('id');
$(this).prop('id');
I have tried adding the handler after the ajax call to populate the modal like this:
$(".server-link").click(function (event) {
event.preventDefault();
$.ajax({
url: $(this).attr("href"),
cache: false,
type: "GET",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
$('#serverDiv').html(data);
$('#serverModal').modal('show');
$('form').submit(function (e) {
var id = $(this).attr(id);
// test to see if handler called
alert(id);
});
},
error: function (jgXHR, textStatus, errorThrown) {
//The commented out message is full of Html but includes compilation errors etc from the server
//alert('An error occured: ' + jgXHR.responseText);
alert(textStatus + ':' + errorThrown);
}
});
});
It's driving me bonkers! I have tried every combination of ideas from various posts with no joy. I need to post using FormData (in one case at least) because there is a file upload (an image) involved. Any assistance is much appreciated.
The problem is that your JavaScript code is running before the form has actually been added to the page. When using AJAX, you need to run whatever JavaScript you need in the callback:
$.get('/some/url', function (result) {
$('#whatever').html(result);
$('form').submit(function(e) {
var id = $(this).prop('id');
// do whatever with id
});
});
Use this instead:
var id = $(e.target).attr('id');

OnClick function using jquery tabs in asp.net

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.

Problems submitting multiple forms with ajaxSubmit / jQuery

I have some code as such to submit multiple forms on my page at once:
$('.photo-edit-form form').ajaxSubmit({
success: function() { console.log('success'); },
error: function() { console.log('error'); }
});
However, no matter how many forms I have, I only ever get one success print out. I've found that I can fix it by using .each on the selected forms like so:
$('.photo-edit-form form').each(function() {
$(this).ajaxSubmit({
success: function() { console.log('success'); },
error: function() { console.log('error'); }
});
});
Is this a problem with the ajaxForm plugin or is this a misunderstanding on my part about how jQuery works? Any input would be greatly appreciated.
The code for the plugin acts like it handles any number at once, but it basically comes down to this:
$.ajax(options);
And the data in that option set comes from .formToArray() which only deals with the first element in the set:
var form = this[0];
So for your question, yes, this is a problem with the plugin, .ajaxSubmit() only works on a single <form> at a time, it doesn't have a .each() internally like most plugins would.
as far as I see it ajaxSubmit does not handle each result from the selector.

Categories

Resources