I have 3 partial views with JS using JQuery in each to post a form and open a new partial view when the form is posted.
What I am finding is that the first time the JS fires it works fine but if I then go to post the form on the new page, I calls the function from the previous page.
The code:
$('#selector').click(function (e) {
var actionName = $(this).attr("id")
e.preventDefault();
e.stopImmediatePropagation();
alert("page1 js being called")
$('#page1Form').submit(function () {
$.ajax({
url: 'Dashboard/Page1/',
data: $(this).serialize(),
type: 'POST',
success: function () {
$.ajax({
url: 'Dashboard/LoadPartial',
data: { viewName: actionName },
type: 'GET',
success: function (d) {
$('#partial').html(d);
}
});
},
});
});
$('#page1Form').submit();
});
The second partial view has a function the same as that but only with the relevant selectors etc and for some reason the previous pages JS is being called as the alert alert("page1 js being called") is appearing in the browser!
Thanks in advance.
If you're loading partial views that means the entire page isn't being refreshed, and as a result the already loaded scripts will still be there. You'll need to remove the event handlers that correspond to the page1 content before adding the new content in:
$.ajax({
url: 'Dashboard/LoadPartial',
data: {
viewName: actionName
},
type: 'GET',
success: function (d) {
$('#selector').off('click'); // remove the click event handler
$('#page1Form').off('submit'); // remove the submit event handler
$('#partial').html(d); // add your new content
}
});
Related
I added a dataLayer push when there's a success 'add to cart' on Shopify, but it fires only when I'm adding a product from the product page, and not from collection page.
any idea why or how to trigger the data layer also when the add to cart happens on the collection page?
Couldn't find anywhere else in the code a place where the add.js is triggered.
Thanks!
Here is the code from the theme.js on Shopify, I emphasized the code I added
cart.prototype.addItemFromForm = function(evt) {
evt.preventDefault();
var params = {
type: 'POST',
url: '/cart/add.js',
data: this.$form.serialize(),
dataType: 'json',
success: $.proxy(function(lineItem) {
**window.dataLayer.push({event: 'addToCart',
common_data: lineItem
})**
this.success(lineItem);
}, this),
error: $.proxy(function(XMLHttpRequest, textStatus) {
this.error(XMLHttpRequest, textStatus);
}, this)
};
I am trying to run jquery function once modal is shown, but I close modal by clicking on the side or one close button and then open I find multiple instances of the inner function running.
<script type="text/javascript">
$(document).ready(function () {
$(".test").click(function () {
var cid = $(this).attr('cid');
$("#post-form").one('submit',function (event){
event.preventDefault();
$.ajax({
url: '{% url 'create_request' %}',
type: 'POST',
data: {
'cid': cid,
'req_num' : $('#request_number').val(),
},
success: function (data) {
console.log("success")
if (data['request']=='0')
{
alert("Request is already there");
}
else if(data['request']=='1')
{
alert("Not enough components:(");
}
$("#exampleModal").modal('hide');
}
})
})
})
})
</script>
test is the class given to button which opens bootstrap modal
post-form is the id given to my form
Attach the submit event listener outside the click function, otherwise you will create one listener per click.
$(document).ready(function () {
$("#post-form").one('submit',function (event){
event.preventDefault();
$.ajax({
url: '{% url 'create_request' %}',
type: 'POST',
data: {
'cid': cid,
'req_num' : $('#request_number').val(),
},
success: function (data) {
if (data['request']=='0')
{
alert("Request is already there");
}
else if(data['request']=='1')
{
alert("Not enough components:(");
}
$("#exampleModal").modal('hide');
}
})
})
})
This will of course break the context for this in $(this).attr('cid');, so you will have to update that to reflect the changes. I'd suggest placing it inside a hidden field in your form, or as an attribute to your modal, whatever is more convenient.
I'm using jquery DataTables to show some tabular data, and I also placed an edit link for each row in said jquery DataTables so that the user can edit data associated with a particular row if needed. ( Also, I have No clue how to use ASP.NET MVC Html helpers within jQuery DataTables so that is why I am using the html link in the following code )
jquery DataTable javascript:
$("#resultCodeTable").dataTable({
"processing": true,
"serverSide": false,
"destroy": shouldDestroy,
"ajax": {
"url": "../Admin/LoadResultCodes",
"type": "GET",
"datatype": "json",
"data": function (data) {
data.actionCodeIDArg = actionCodeIDInQuestion;
}
},
....................................
............................
..............
columnDefs: [
{
{
targets: 1,
searchable: false,
orderable: false,
name: "EditResultCodeInQuestionReasonForArrears",
"data": "ID",
render: function (data, type, full, meta) {
if (type === 'display') {
data = '<a class="editResultCodeInQuestionReasonForArrears" href="javascript:void(0)" data-id="' + full.ID + '">Edit RFAs</a>'
}
return data;
}
},
....................................
............................
..............
Clicking on the aforementioned link will ensure that the point of execution reaches the following jQuery Event Handler method:
jQuery Event handler method/ function Javascript
$('#resultCodeTable').on('click', '.editResultCodeInQuestionReasonForArrears', function () {
console.log(this.value);
navigateToAParticularResultCodeAssociatedReasonForArrearsList($(this).data('id'));
});
The jQuery Ajax call successfully invokes the C# Controller's action because I see the Visual Studio's Debugger's point of execution reach said Controller's action, however, it fail to navigate to the view that I want to show.
jquery / javascript:
function navigateToAParticularResultCodeAssociatedReasonForArrearsList(resultCodeTable_ID) {
console.log(resultCodeTable_ID);
$.ajax({
url: '../Admin/NavigateToAParticularResultCodeAssociatedReasonForArrearsList',
type: 'POST',
dataType: 'json',
contentType: "application/json;charset=utf-8",
data: "{'" + "resultCodeTable_IDArg':'" + resultCodeTable_ID + "'}",
cache: false,
}).done(function (response, status, jqxhr) {
})
.fail(function (jqxhr, status, error) {
// this is the ""error"" callback
});
}
C#: ( in my AdminController.cs )
public ActionResult NavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg)
{
AParticularResultCodeAssociatedReasonForArrearsListViewModel aParticularResultCodeAssociatedReasonForArrearsListViewModel = new AParticularResultCodeAssociatedReasonForArrearsListViewModel();
aParticularResultCodeAssociatedReasonForArrearsListViewModel.ResultCodeTable_ID = resultCodeTable_IDArg;
return View("~/Areas/Admin/Views/Admin/AdminModules/Auxiliaries/AParticularResultCodeAssociatedReasonForArrearsList.cshtml", aParticularResultCodeAssociatedReasonForArrearsListViewModel);
}
Razor / Html: (In my \Areas\Admin\Views\Admin\AdminModules\Auxiliaries\AParticularResultCodeAssociatedReasonForArrearsList.cshtml view )
#model Trilogy.Areas.Admin.ViewModels.Auxiliaries.AParticularResultCodeAssociatedReasonForArrearsListViewModel
#{
ViewBag.Title = "AParticularResultCodeAssociatedReasonForArrearsList";
}
<h2>AParticularResultCodeAssociatedReasonForArrearsList</h2>
Could someone please tell me how I can change the code so that the view shows up after the jquery Ajax invocation?
May be on .done function you will get the view in the response, you need to take that response and bind it to your control
You call the controller via AJAX, and sure it hits the controller action method, and the controller returns a view but this is your code that deals with whatever is returned from the AJAX call (from the controller):
.done(function (response, status, jqxhr) {})
You are doing absolutely nothing, so why would it navigate anywhere.
A better question you need to ask yourself, instead of fixing this, is why would you use AJAX and then navigate to another page. If you are navigating to a whole new page, new URL, then simply submit a form regularly (without AJAX) or do it via a link (which the user will click). Use AJAX post if you want to stay on the same page and refresh the page's contents.
#yas-ikeda , #codingyoshi , #code-first Thank you for your suggestions.
Here are the modifications that I had to make to resolve the problem(please feel free to suggest improvements):
Basically, I had to end up creating 2 separate Action methods to resolve the problem.
In the jquery/Javascript code below, it is important to note the first action method '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList'
function navigateToAParticularResultCodeAssociatedReasonForArrearsList(resultCodeTable_ID) {
console.log(resultCodeTable_ID);
$.ajax({
url: '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList',
type: 'POST',
dataType: 'json',
contentType: "application/json;charset=utf-8",
data: "{'" + "resultCodeTable_IDArg':'" + resultCodeTable_ID + "'}",
cache: false,
}).done(function (response, status, jqxhr) {
window.location.href = response.Url;
})
.fail(function (jqxhr, status, error) {
// this is the ""error"" callback
});
}
The purpose of the 1st action method called '../Admin/RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList' is to retrieve a url within a Json object.
[HttpPost]
public ActionResult RedirectToNavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg)
{
var redirectUrl = new UrlHelper(Request.RequestContext).Action("NavigateToAParticularResultCodeAssociatedReasonForArrearsList", "Admin", new { resultCodeTable_IDArg = resultCodeTable_IDArg });
return Json(new { Url = redirectUrl });
}
The purpose of the 2nd action method is to ultimately navigate to the ASP.NET MVC View that I want to show.
public ActionResult NavigateToAParticularResultCodeAssociatedReasonForArrearsList(int resultCodeTable_IDArg)
{
AParticularResultCodeAssociatedReasonForArrearsListViewModel aParticularResultCodeAssociatedReasonForArrearsListViewModel = new AParticularResultCodeAssociatedReasonForArrearsListViewModel();
aParticularResultCodeAssociatedReasonForArrearsListViewModel.ResultCodeTable_ID = resultCodeTable_IDArg;
aParticularResultCodeAssociatedReasonForArrearsListViewModel.RFACodeList = actionCodeResultCodeBusinessService.GetSpecificResultCodeRFACodeList(resultCodeTable_IDArg);
return View("~/Areas/Admin/Views/Admin/AdminModules/Auxiliaries/AParticularResultCodeAssociatedReasonForArrearsList.cshtml", aParticularResultCodeAssociatedReasonForArrearsListViewModel);
}
However, I Dislike the fact that I have to use 2 action methods to navigate to the desired asp.net mvc view, therefore, please feel free to suggest improvements or even a totally different better solution.
Im using this cool javascript scheduler. At first I load it in my page by
function get_dependencies() {
//event calendar
$(".myscheduler").dhx_scheduler({
xml_date: "%Y-%m-%d %H:%i",
date: new Date(2014, 4, 25),
mode: "month"
});
scheduler.load($("body").attr("data-link") + "/core/plugins/dhtmlcalendar/events.xml");
}
and then call the function
$(window).load(function(){
get_dependencies();
});
and then when any of navs is click (navs associated with the ajax page stuff) call the page and render the scheduler again
$.ajax({
url: '/ajax-page',
type: 'post',
dataType: 'html',
beforeSend: function () {
$("#loading").show();
},
data: {
page: this_tab_content_link,
_token: $("body").attr("data-token")
},
success: function (data) {
$(".active_tab_content").html(data);
if ($(this).hasClass("reload_dependencies")) {
get_dependencies();
}
$("#loading").hide();
}
});
but sadly the scheduler, didn't render (no calendar scheduler is showing) after the html data (the ajax page response) is put in to the specified container. Any ideas, help, suggestions, recommendations, help?
Set relevant context to ajax callback, this in your code is jqXHR option object. Set ajax option context to this:
$.ajax({
context: this,
/*...*/
});
When an POST is made to the controller, the controller responds with exactly what I want the browser to render. But the browser does not render the response. I've verified the response is good in Fiddler.
The code below shows what I think is relavent code. The controller action method that returns the response, part of the template that has the mvc helper code, javascript/jquery code that fires the ajax call with the form inputs.
I want to use the FormCollection. Why doesn't the browser render the response and what can I do to fix it?
BoMController
public ActionResult GetBillOfMaterialsView(FormCollection frmColl){
// snipped out model interaction
return PartialView("~/Views/Project/Index.cshtml", project);
}
Index.cshtml
#using (Html.BeginForm("GetBillOfMaterialsView", "BoM", FormMethod.Post, new {id = "frmGetBom"})) {
// selProj input select code removed for brevity
}
function submitGetBoM() {
var frmGetBom = $('#frmGetBom');
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize()
});
}
$(document).ready(function() {
$('#selProj').selectmenu( {
select: function(){submitGetBoM()}
}).addClass("overflow");
});
Invoking $.ajax alone doesn't append the response from the server to the document, you have to use the success callback to manually fetch the response and append it.
For example:
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize(),
success: function(response) {
$('#someContainerId').html(response);
}
});
Alternatively, use load() that is a shorthand to the above:
$('#someContainerId').load(frmGetBom.attr('action'), frmGetBom.serializeArray());
See Documentation
Your client code doesn't do anything with the returned values from the server:
function submitGetBoM() {
var frmGetBom = $('#frmGetBom');
$.ajax({
type: 'POST',
url: frmGetBom.attr('action'),
data: frmGetBom.serialize(),
success: function() { alert('ok'); }
});
}
This would popup an alert on success.