Previous ajax request changes the post URL for next form submit - asp.net-mvc

I am making a jQuery ajax request in a asp.net mvc page:
$.ajax({
type: "POST",
url: "/Home/Go",
data: dataObj,
success: function (data) {
// update html here
}
}
});
This call is within a page, which has a form and other elements which submit to other url (lets say "/Home/Do"). Now after the ajax call returns, If I click on any other element the form still submits to url1 instead of url2
Note I tried adding a "return false" statement to click event handler where the ajax call is made. But even this did not help
The ajax call is made within the jQuery dialog:
$('#myDialog').dialog({ buttons:
[
{
text: 'Next',
click: function () { HandleNext(); return false; }
}
],
title: 'Dialog-Title'
});
function HandleNext()
{
$.ajax({
type: "POST",
url: "/Home/Go",
data: dataObj,
success: function (data) {
// update html here
}
}
});
return false;
}
Anybody faced a similar issue? any solutions?

return false in the click handler is mandatory for ALL ajax requests. The web browser will visit the url otherwise. In other words: The ajax request is made first and then a regular request.
No urls can automagically be replaced with other urls. You either do it in your javascript code, or in your action/view.

Related

How to call partial view in script section

I am new in MVC. I have a button when i click it should go to a partial view and return data i need. I do not know how should i achieve that:
Main view:
<script>
if ($("#btnFilter").click(function () {
#{Html.RenderPartial("partialView"); }
}));
</script>
partial view
var dtDrpVals = new selectedDateDrpdnVal();
debugger;
$.ajax({
dataType: "json",
type: "POST",
url: "#Url.Action("controller","Dashbrd")",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ "regionalManager": dtDrpVals.drpValue, "dtFrom": dtDrpVals.fromDate, "dtTo": dtDrpVals.toDate }),
success: function (result) {
}
});
In the html define a div where you want the partial to be located in and in the ajax success put the result of the call to the controller into that div, assuming you are returning a partialview:
$("#The id of the div").html(result);
The best way to do it is Make an Action in your ASP.NET controller that returns a Partial View and in your jquery, you should make an AJAX call to that action with required parameters that eventually will return a Partial View to your Jquery, and the data you will receive from your action will be of type 'HTML' and not JSON.
once you receive HTML data in your success function of AJAX call you can replace it with any Div.

jquery mobile prevent browser reload

I added data to the page in Ajax and then I changed to the page
$.mobile.changePage('#postDetails', { transition: "slide" })
but then when I refresh the browser all the contents I added with the Ajax is not there any more.
refreshing a page will remove Ajax data, to resolve that issue you need to add your Ajax call inside pageshow event like following
$(document).on("pageshow","#postDetails",function(){
$.ajax({
url: postDetailsUrl,
type: "post",
data: {id: id},
beforeSend: function () {
$.mobile.loading("show");
},
complete: function () {
$.mobile.loading("hide");
},
success: function (data) {
$('#commentList').html(data);
$('#commentsNum').text($('#commentList .comment').length);
initCommentPage();
},
error: function (requestObject, error, errorThrown) {
alert("Error in communication");
}
});
})
now this ajax request is in pageshow event so every time popstDetails page is shown it will make a ajax call to postDetailsUrl and show the data in commentList element.
to know more about page events see gajotres's blog

Using PagedList.Mvc for partial page

I have four different tabs in one page and data for each tab is rendered by an ajax call using partial page. Data for tab is loaded by ajax post.
ajax call:
$('#movieDatabase').click(function () {
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'html',
type: 'POST',
url: '/Admin/GetMovieDatabase',
data: {},
success: function (data) {
$('#view16').html(data);
},
failure: function (response) {
alert('error');
$('#view16').html(response);
}
});
});
This ajax call rendered the partial page. Now I want to do is paging the movie came from database.For this I use PagedList.Mvc. But problem occurred in navigating movie from one page to another. It is done by:
#Html.PagedListPager((IPagedList)Model.MovieInforamtions, page => Url.Action("GetMovieDatabase", new { page }))
But when I click on next page it gives page not found error as I have not written any action in HTTPGet. And If I made above call by HTTPGet, I couldnot render all page but only partial page. My action is..
[HttpPost]
public ActionResult GetMovieDatabase(int? page)
{
var AdminGetMovieDatabaseViewModel = new AdminGetMovieDatabaseViewModel();
var allMovie = _AdminService.getAllMovieInfo();
var pageNumber = page ?? 1;
// if no page was specified in the querystring, default to the first page (1)
var onePageOfMovie = allMovie.ToPagedList(pageNumber, 5);
// will only contain 5 products max because of the pageSize
AdminGetMovieDatabaseViewModel.MovieInforamtions = onePageOfMovie;
return PartialView("MovieDataBasePartialPage", AdminGetMovieDatabaseViewModel);
}
Now How can I render the next page like in ajax call which is done previously?
I put the code in javascript section inside the partial view and works for me.
<script language ="javascript" type="text/javascript">
$('#movieDatabase').click(function () {
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'html',
type: 'POST',
url: '/Admin/GetMovieDatabase',
data: {},
success: function (data) {
$('#view16').html(data);
},
failure: function (response) {
alert('error');
$('#view16').html(response);
}
});
});
</script>

jQuery Ajax Form Submit Fails

I am developing an MVC4 mobile app that uses several forms which are loaded into a section on the layout via ajax. I've got jQuery mobile set with Ajax turned off so I can manage the Ajax myself. Most of the forms work fine, the load and submit via ajax as they should. However, so far there is one form that refuses to fire the form submit and submit the form via ajax like the rest. First, the form is loaded when a user clicks to add a contact and this works fine:
// Handle the add contact button click
$('#btnAddNewContact').on('click', function (e) {
e.preventDefault();
// Make sure a location was selected first.
var locationID = $('#cboLocation').val();
if (locationID.length === 0) {
//$('#alertTitle').text('REQUIRED');
$('#alertMsg').html("<p>A Contact must be associated with a Location.</p><p>Please select or add a Location first.</p>");
$('#alertDialogDisplay').click();
} else {
SaveOpportunityFormState();
$.cookie('cmdLocationId', locationID, { path: '/' });
$.mobile.loading('show');
$.ajax({
url: '/Contact/Add',
type: 'GET',
cache: false,
success: function (response, status, XMLHttpRequest) {
$('section.ui-content-Override').html(response);
// Refresh the page to apply jQuery Mobile styles.
$('section.ui-content-Override').trigger('create');
// Force client side validation.
$.validator.unobtrusive.parse($('section.ui-content-Override'));
},
complete: function () {
$.cookie('cmdPreviousPage', '/Opportunity/Add', { path: '/' });
AddContactLoad();
ShowSearchHeader(false);
$.mobile.loading('hide');
},
error: function (xhr, status, error) {
// TODO - See if we need to handle errors here.
}
});
}
return false;
});
Notice that after successfully loading the form the AddContactLoad() function is fired. This works fine and here is that code:
function AddContactLoad() {
$('#contactVM_Phone').mask('(999) 999-9999? x99999');
$('#frmAddContact').on('submit', function (e) {
e.preventDefault();
if ($(this).valid()) {
$.mobile.loading('show');
$.ajax({
url: '/Contact/Add',
type: 'POST',
cache: false,
data: $(this).serialize(),
success: function (response, status, XMLHttpRequest) {
if (!response) { // Success
ReturnToAddOpportunity();
} else { // Invalid Form
$('section.ui-content-Override').html(response);
// Force jQuery Mobile to apply styles.
$('section.ui-content-Override').trigger('create');
// Force client side validation.
$.validator.unobtrusive.parse($('section.ui-content-Override'));
AddContactLoad();
$.mobile.loading('hide');
}
},
complete: function () {
},
error: function (xhr, status, error) {
// TODO - See if we need to handle errors here.
}
});
}
return false;
});
$('#btnCancel').on('click', function (e) {
e.preventDefault();
// See where add contact was called from.
var previousPage = $.cookie('cmdPreviousPage');
if (previousPage.indexOf("Detail") >= 0) {
ReturnToOpportunityDetails();
} else {
ReturnToAddOpportunity();
}
return false;
});
}
If I click the cancel button, that code is fired so I know this is working too. Here is my form code:
#using (Html.BeginForm("Add", "Contact", FormMethod.Post, new { #id = "frmAddContact" }))
{
#Html.ValidationSummary(true)
#Html.AntiForgeryToken()
-- Form Fields Here --
<div class="savecancel" >
<input type="submit" value="Save" data-mini="true", data-theme="b", data-inline="true" />
Cancel
</div>
}
As you can see the form is named frmAddContact and that is what the AddContactLoad() function is attaching the submit event to. To save my sole I cannot figure out why the form does not submit via the ajax post like every other form in the app. Am I missing some kind of initialization, I just don't know. If anyone can please help I'd really appreciate it!!
As it turns out, I had created a custom unobtrusive Ajax validator for a phone number then copied and pasted it to do the same with a zip code. Unfortunately in the process I forgot to rename a variable and thus an error was occurring in the validation script which caused the problem. In the mean time, if you're reading this, you might take a note of the code here and how to inject HTML into a page via Ajax and jQuery mobile. I've never found this in a book or on the web and it contains some very useful methodology and syntax. On the form submit the reason I'm checking for the empty response is I just return null from the controller to validate the form was valid and the save worked in which case I send them to a different HTML injection i.e. that page they originally came from. If null is not returned I inject that page with the HTML containing the original form and error markup so the user can make corrections then resubmit. I'm also calling a form load method that attaches handlers to the HTML once it's injected into the main page. Hope this helps somebody!

Dynamically added link action produces 'This request has been blocked...' error

When I add category in controller action I return JSON object:
return Json(new { categoryName = category.Name, isPrimary = isPrim ? "1" : "-1", categoryId = categoryId }, JsonRequestBehavior.AllowGet);
In JS handler function I add item on page:
...
var totalLink = "<li style='color: #bbbbbb;'>" + result.categoryName + "<a class='removeCategoryButton' href='#lnk#'>remove</a></li>";
var lnk = '#Url.Action("RemoveCategoryFromLocation", "Location", new{locationId = Model.Location.TicketId, categoryId=-1})';
totalLink = totalLink.replace('#lnk#', lnk);
totalLink = totalLink.replace('-1', result.categoryId);
$('#otherCategories').append(totalLink);
...
When I click on remove link I call the following function:
$(function () {
$('.removeCategoryButton').click(function (event) {
event.preventDefault();
$.ajax({
url: this.href,
type: 'POST',
context: this,
success: function (result) {
if(result.categoryName == 1) {
$(this).closest('li').remove();
}
}
});
return false;
});
});
But I get the following error:
This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet.
This error happens only when I add item and want to remove it as soon after add on page. If I refresh page and click on remove link it works without problem.
Just to note when I get the error from above category is removed, so call works it just from some reason pop this error.
You seem to be adding the remove links dynamically and yet you have subscribed to the .click event handler only once when the DOM is ready. So make sure you do it in a lively manner. But since the .live() method is deprecated, depending on the jQuery version that you are using you should use either .delegate() or the .on() methods.
So with the latest version of jQuery it is recommended to use .on():
$(document).on(events, selector, data, handler);
$(document).on('click', '.removeCategoryButton', function () {
$.ajax({
url: this.href,
type: 'POST',
context: this,
success: function (result) {
if(result.categoryName == 1) {
$(this).closest('li').remove();
}
}
});
return false;
});
Notice that you no longer need to wrap this in a document.ready callback.

Resources