Javascript included in MVC partial view only runs the first time - javascript

I have a button which I use to load a partial view via jquery ajax call, which on success, just replace a div holder by the json string being returned.
The partial view consists of some javascript and html tags. I have to set the jquery.ajax dataType: "html" in order to get the javascript executed in the partial view when it is loaded.
In the parent view:
$("#test2Div").on("click", function () {
$.ajax({
type: "POST",
url: '#Url.Action("GetMainSolution", "Solutions")',
data: { IdEjercicioSolucion: 9 },
cache: false,
dataType: "html",
success: function (response) {
$("#placeHolder").html(response.ViewContent);
}
});
});
The problem is that this is only working fine for the first time I load the partial view. Once it is executed for the first time, it seems that those javascript included in the partial view being rendered are not being executed anymore or something is missed in the DOM. If I refresh the whole page, with F5 and load the partial view again, it will work again for the first time.
Please, any ideas?
EDIT 1: add more sample code:
Parent view: This is the main view. It displays another another partial view which has some fields and a button. Clicking that button invoke UpdateChViewerLayoutForm function, which trys to load the following partial view into aqviewerholder div.
<div id="dvContainer">
<div class="container">
<div class="row">
#Html.Partial("SolutionsCursoSelectedPartial", Model)
</div>
<div class="row">
<div id="aqviewerholder"></div>
</div>
</div>
</div>
<script type="text/javascript">
function UpdateChViewerLayoutForm(s, e) {
$.ajax({
type: "POST",
url: '#Url.Action("GetSolucionsAQV", "Solutions")',
data: { IdES: s.GetValue() },
success: function (response) {
$("#aqviewerholder").html(response.ViewContent);
}
});
}
</script>
Partial view (SolutionsAQv):
#Code
If Model IsNot Nothing Then
#Html.Raw(Model.TextoHTML)
End If
End Code
<script src="~/Content/AQv/rm.js" type="text/javascript"></script>
<script src="~/Content/AQv/bm.js" type="text/javascript"></script>
<script src="~/Content/AQv/nn.js" type="text/javascript"></script>
Please note that the content delivered to model needs to be parsed using the scripts in partial view.
This is working properly in the first load, but not in the following ones. If refresh the whole page, it works again.
I guess it may be something related to the fact that partials views via ajax do not execute javascript? or that javascript is not finding the target in the DOM in the following exceutions?... but I dont really know how to continue...
Thanks a lot

One possibility is that your partial view includes same jQuery or other javascript bundles as the ones in 'main view'. Once they are rendered for the first time, you will have two such sets (one from your main view and one from your partial view). Make sure you have only one bundle on your webpage and not repeating bundles.
This happened to me.
P.S: This is one possibility! No way I'm saying this is the only reason. I just thought this could be a possibility

Related

How to put a Partial View into a div in JavaScript (with jQuery)

I have ,MyPartialView.cshtml':
<div id="partialDiv">some content</div>
an 'index.cshtml':
<div id="mainDiv"> </div>
and an 'index.js'.
The 'index.js' should do sth like:
$('mainDiv').html($('#partialDiv'))
to put the partial view into the main div.
(writing #<text> <div> #Html.Partial("MyPartialView")</div></text>) in my .cshtml works, but I need to change the content dynamically. Therefore, I thought maybe there is an equivalent in JavaScript for 'Html.Partial'
(Or is there another way to get a Partial View without an AJAX Call)
#Html.Partial("MyPartialView") used only to render single partial view file (also with #Html.RenderPartial()). You can use AJAX to call controller action which returns partial view:
AJAX Request
$.ajax({
type: 'GET',
url: '#Url.Action("ActionName", "ControllerName")',
// other settings
success: function (result) {
$('mainDiv').html(result);
}
});
Controller Action
[HttpGet]
public ActionResult ActionName()
{
// do something
return PartialView("MyPartialView");
}
Note that there's no equivalent of calling partial view in JS, because you need to make request to server which can't be simply handled by standard JS functions.
cshtml files are rendred in server side. you can't load it using just JavaScript. the perfect way is using Ajax by calling an Action that return your partial view

jQuery not working in MVC partialview after moving the JavaScript code to separate file and reference the file in a script tag cause problems

I am new to web development and I am using .net core MVC with VS2017, and trying to load several partial views inside a div (section1 and section2) using ajax and javascript.
My index page:
<div>
<a asp-action="setupprogram" asp-controller="Setup" data-target="Section1" class="section1">Setup Programs</a>
</div>
<br />
<div id="Section1"></div>
<br />
<div id="Section2"></div>
<br />
When I include the javascript code inside the chtml it run perfectly, but when I remove the jQuery code and put it inside site.js, it didn't work
My site.js code:
$(document).ready(function () {
$("#Sform").submit(function (e) {
e.preventDefault();
var urlsx = $('#UrlsX').val();
var urls = $('#Urls').val();
$.ajax({
url: urls,
type: "POST",
dataType: "html",
data: $('#Sform').serialize(),
success: function (data, textStatus, xhr) {
$('#Section2').html(data);
$("#Section1").load(urlsx)
},
error: function (xhr, textStatus, errorThrown) {
$("#Section2").html(xhr.responseText);
}
});
});
$('.section1').click(function (e) {
e.preventDefault();
$("#Section1").show();
$('#' + $(this).data("target")).load($(this).attr("href"));
});
$('.section2').click(function (e) {
e.preventDefault();
$("#Section1").show();
$("#Section2").show();
$('#' + $(this).data("target")).load($(this).attr("href"));
});
});
the simple way to solve this issue is to include the script tag
<script src="~/js/site.js"></script>
at each partial view to load the JavaScript code after the DOM load and to be able to find the required objects, accounting to this post and also this post
Mmy problem is that the JavaScript code make the page load time too long after few clicks and it themes that the code is looping inside my C# action several times and making the page load time unaccepted.
Also the second partial view do not recognize the code and load in a new page rather than being rendered in the Section2 div.
The site.js file is referanced in the _Layout.cshtml:
<environment names="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js"></script>#*asp-append-version="true"*#
</environment>
The first patial view that load in section one is as follwoing :
#foreach (var p in Model)
{
<div>
#p.ProgName
<a asp-action="setupprogramEdit" asp-controller="Setup" asp-route-id="#p.ProgID" data-target="Section2" class="section2">Edit</a>
|| <a asp-action="setupprogramdelete" asp-controller="Setup" asp-route-id="#p.ProgID" data-target="Section2" class="section2">Delete</a>
</div>
}
<div>
<a asp-action="setupprogram" asp-controller="Setup" data-target="Section1" class="cancel2">cancel</a>
</div>
First : is it better to keep the JavaScript code inside the chtml view page ?\
Second : any idea how to come over this issue, in case i decided to move the JavaScript code into a separate file ?
Is best to keep the jquery code in a separate file and include that file in your view.
If your page loading time is big, why you don't load the partials when you click the button instead of loading them all at once and keeping them hidden?
Also you are requesting the same partials multiple times?

How do handle dynamically loaded javascript and avoid HTML collision

I've been smashing my head against a brick wall for the past 3 hours trying to figure out how to handle this.
Here's what I am trying to:
When I press a viewProduct button, it loads a page product/view/{id} via a simple jQuery ajax call and insert it in a div.
Here is my main page (index.php)
<script type="text/javascript">
$(function() {
$(".viewProduct").on('click', function() {
var productID = $(this).data('id');
$.ajax({
type: 'GET',
url: "http://mywebappurl.com/product/view/" + productID,
success: function(view) {
$("#productInfo").html(view);
}
});
});
</script>
<button class="viewProduct" data-id="11">View Product</button>
<div id="productInfo"></div>
Product/view contains some HTML (including viewParentProduct) and some javascript.
Here product/view.php
<script type="text/javascript">
$(function() {
// More javascript here....
$("#viewParentProduct").on('click', function() {
var parentProductID = 15; // This number changes depending on the product and comes from PHP
$.ajax({
type: 'GET',
url: "http://mywebappurl.com/order/view/" + parentProductID,
success: function(view) {
$("#parentProductInfo").html(view);
}
});
});
</script>
<button id="viewParentProduct">View parent product</button>
<div id="parentProductInfo"></div>
So far, it works fine. The dynamically loaded javascript executes perfectly. The problem comes when the the parent product also has a parent product. So if I press the viewParentProduct , it loads the same page (product/view) and inject it in the dom, duplicating the HTML elements and javascript.
Visually:
STAGE 1: Click on viewProduct --> product/view/11 is injected into productInfo div
STAGE 2: Click on viewParentProduct --> product/view/15 is injected into parentProductInfo div
STAGE 3: Click on viewParentProduct --> product/view/{someOtherParentProductID} is injected into parentProductInfo div
At this point I am screwed. Since the same HTML/Javascript has been injected in the DOM twice, the next time I press on viewParentProduct, it'll trigger the wrong button and/or load the content of product/view in the wrong parentProductInfo div.
Of course I could do something like this but it's pretty ugly:
$(".viewProduct_11").on('click', .....
<button class="viewProduct_11" data-id="11">View Product</button>
<div id="productInfo_11"></div>
// Where 11 comes from PHP ex: <?php echo $productID; ?>
So my question is: Is there a way to sort of "namespace" a set of javascript-HTML or do you know a way to fix this problem ? Even if I namespaced the javascript, the HTML element's IDs would still be duplicated.
I'm really out of ideas!
-----------------------EDIT-----------------------
I need to have the javascript inside the view (product/view) because it's rather complex. In fact it has nothing to do with the simple snipped I used as an example in this question. I'd rather have the javascript related to the product/view page inside the view itself to improve cohesion. In reality, when clicking on the viewProduct button, the product/view page is loaded in a modal (a div with an overlay) and there can be multiple modal overlapping each other with the same HTML/javascript code coming from product/view. I could work around the javascript collision by wrapping the product/view's javascript in a namespace, however the HTML and the DOM elements and their ID will still be problematic. Hence why I'm looking for a way for namespacing a block of javascript AND HTML...somehow. I'm clueless.
Try this:
index.php
<script type="text/javascript">
$(function() {
$("body").on('click', '.viewProduct', function() {
var elem = $(this),
productID = elem.data('id');
$.ajax({
type: 'GET',
url: "http://mywebappurl.com/product/view/" + productID,
success: function(view) {
elem.next().html(view);
}
});
});
</script>
<div class='viewWrapper'>
<button class="viewProduct" data-id="11">View Product</button>
<div class="productInfo"></div>
</div>
product/view.php
<div class='viewWrapper'>
<button class="viewProduct" data-id="15">View Parent Product</button>
<div class="productInfo"></div>
</div>
// Where 15 comes from PHP ex: <?php echo $productID; ?>
JavaScript from main page will be working for new loaded content.
ex.: http://jsfiddle.net/BV66Z/1/

TineMCE doesn't initiate ajax-loaded textarea

I use $.ajax() to load this piece of html into a div
<div class="board-container">
<form method="post" action="functions.php">
<input type="hidden" name="function" value="set_boards">
<div class="row-fluid">
<div class="span6">
<h3 class="dark">Student Board</h3>
<textarea id="board_students" name="board_students">
</textarea>
<br>
</div>
<div class="span6">
<h3 class="dark">Instructor Board</h3>
<textarea id="board_instructors" name="board_instructors">
</textarea>
<br>
</div>
</div>
Update Boards
</form>
</div>
<script src="libs/tinymce/tinymce.min.js"></script>
<script src="js/board.js"></script>
And in the board.js, there's simply a TinyMCE initiation function.
$(function()
{
tinymce.init({
menubar : false,
height: 700,
selector: "#board_students"
});
});
The ready() function should be called automatically due to ajax request. I've tested with alert and I know the function gets called.
The code works if the html is in the div by default, but when loaded through ajax, nothing happens. Why is that?
This happens because your ajax loads content asynchronously and your tiny initialization function happens synchronously, may be the initialization happens before the content is placed into your dom. The another thing is you shouldn't load scripts in html data .
To solve this
If you want to load script async means you have to create a script tag element using js like
var jsonp = document.createElement("script");
jsonp.type = "text/javascript";
jsonp.src = "libs/tinymce/tinymce.min.js";
document.getElementsByTagName("body")[0].appendChild(jsonp);
or You can include tinymce.min.js in page itself and initialize the div after the content is loaded like
$.ajax({
url: url,
type: type,
data: data,
success: function(htmlData){
$('#DivId').append(htmlData);
//here internalize tiny mice when its available in dom
tinymce.init({
menubar : false,
height: 700,
selector: "#board_students"
});
}
});
Try this and let me know if this works ... !!!
The reason this is happening is because, The ajax adds your content AFTER --page load--. Therefore, it's not reading and adding your code to the DOM, because you're adding this after the page is already loaded.
As many said, you can preload this info, or if you want to use AJAX.
The easiest way to initialize your code would be to add a .complete function at the end of your ajax call. This says that when the ajax function is done running, continue with this action.
$.ajax({
type: "POST", #GET/POST
url: "some.url",
data: {}
})
.complete(function() {
tinymce.init({
menubar : false,
height: 700,
selector: "#board_students"
}
});
Jquery Ajax Call
The <script> blocks in your case will start execute in the same moment asynchronous, and just because tinymce is the biggest script, tinymce.init will fail.
You need load the scripts as additional cascade of ajax call:
$.get(...., function (){// first level, getting the html
$.getScript(...., function (){// second level, getting <script src="libs/tinymce/tinymce.min.js"></script>
// executing or loading js/board.js
});
});

ajax-loaded script not functioning

This code below is loaded via ajax:
<div class="main">
//some content
</div>
<div class="advanced">
//some content
</div>
<div class="other">
//some content
</div>
<div class="pass">
//some content
</div>
<script>$('.advanced,.other,.pass').hide();</script>
They hide fine when loaded normally, but when loaded via ajax it doesn't work anymore. Why is it so? I'm not really sure if $.on() would really help here.
If the example above is loaded via jQuery ajax, why not just call the
$('.advanced,.other,.pass').hide();
upon completion of the ajax request?
For example:
$.ajax({
url: "Your AJAX URL",
dataType: 'html',
type: "POST",
success: function (json) {
// Add you elements to the DOM
},
complete: function () {
$('.advanced,.other,.pass').hide();
}
});
According to jQuery
any embedded JavaScript inside the retrieved data is executed before the HTML is returned as a string.
this could mean that your script executed first, before you managed to do anything with it.

Categories

Resources