How to load javascript code dynamically - asp.net-mvc

The main page is an .aspx file. I'm trying to generate a popup. When user clicks the Send Email, a javascript on the page calls the openEmailPopup function, shown below.
function openEmailPopup(taskId, popupElementName, gridElementName) {
$("#" + popupElementName).dialog({
width: 1300,
height: 500,
draggable: false,
resizable: false,
modal: true,
open: function () {
$.get("/Resources/Sendmail", function (data) {
$('#masterPvlEmailGrid').html(data);
});
//more code here...
}
});
}
The problem is that the SendEmail.cshtml file depends on some javascript file.
<script language="javascript" src="../../Scripts/file1.js"></script>
<script language="javascript" src="../../Scripts/file2.js"></script>
<script language="javascript" src="../../Scripts/file3.js"></script>
<script language="javascript">
var sendEmailViewModel = new SendEmailViewModel();
var seUploadFilesViewModel = new UploadFilesViewModel();
$(function () {
sendEmailViewModel.Init();
});
</script>
When the response of the ajax call is returned, those above javascript don't execute. There are two solutions for that. Either I add javascript reference on the .aspx page. However, to do that, I also need to add a content placeholder element in the master page. The big problem with that is the actual aspx file has a master page that is nested 2 times deep in other master pages.
Many people relies on those master pages, I want to make sure that there are solutions to that before I touch them.
What about loading and executing those javascript file dynamically? I've done some researches but, I still don't understand how it work with jquery.
Any idea?
EDIT
This is how I'm calling those file.
$.getScript("/Scripts/file1.js", function () {
});
$.getScript("/Scripts/file2.js", function () {
});
$.getScript("/Scripts/file3.js", function () {
});
When I check google tools, I see that all the file being loaded.

You could use jQuery's getScript method, which allows you to load javascript over HTTP and then execute it:
http://api.jquery.com/jquery.getscript/

You might want to look at an AMD like RequireJS (http://requirejs.org/). RequireJS is designed to load JavaScript resources as needed, so you would not need to load them in the main page. In your example, all three files could be returned asynchronously for your popup form.

I am not sure if this will solve your problem because I cannot test it right now. Could you try this out?
function openEmailPopup(taskId, popupElementName, gridElementName) {
$("#" + popupElementName).dialog({
width: 1300,
height: 500,
draggable: false,
resizable: false,
modal: true,
open: function() {
var deferreds = [];
//Store a deferred into the array
function addDeferred(url) {
deferreds.push(
$.getScript(url)
.done(function() {
console.log("Module loaded: " + url);
})
.fail(function(ex) {
console.error(ex);
})
);
};
//Call the scripts
addDeferred("/Scripts/file1.js");
addDeferred("/Scripts/file2.js");
addDeferred("/Scripts/file3.js");
//When all the scripts has been loaded....
$.when.apply($, deferreds)
.done(function() {
$.get("/Resources/Sendmail", function(data) {
$('#masterPvlEmailGrid').html(data);
});
})
.fail(function(ex) {
console.log(ex);
});
//more code here...
}
});
}

Related

How to show loading div in my view with json result

I am using a loading div in my MVC application. so i am getting json result value and showing a kendo grid. Because of more data it is taking time so for that purpose i used this but unfortunately it's not working.
Below is my code
This is my script used in the view
<script type="text/javascript">
$(document).ready(function () {
var action = "#Url.Content("~/Dashboard/ChartInitialDataBinding/")";
$('#spinner').show()
$.getJSON(action, null, function(something)
{
$('#spinner').hide()
});
});
</script>
This is my loading div
<div id="spinner" style="display:none">
Loading...
</div>
Thanks
You should know from documentation, that getJSON() is just wrap above ajax jquery function.
So don't you want to put your spinner not only in this function, but with all ajax requests? I think it's better, becouse you can define this in onle place and don't thik anymoreabout this problem.
In your Layout View just add this script, after your jquery library loaded:
$(document).ready(function () {
$.ajaxSetup({
beforeSend: function () {
$('#spinner').show()
},
complete: function () {
$('#spinner').hide()
},
error: function () {
$('#spinner').hide()
}
});
});
You can read more about $.ajaxSetup here.
Here is a list of things to check/fix:
-add semicolons after $('#spinner').show() and $('#spinner').hide()
-make sure you have included jQuery
-check if spinner is in view when removing "display:none"

JQuery-ui Tabs - reload page with completely new content not working

I'm loading in a report and displaying it with jquery-ui in tab format. The report is returned by an ajax call in json, and a function is formatting it into HTML. Example code below:
<div id="reportdiv">
</div>
<script>
function displayreport(objectid)
{
$( "#reportdiv" ).hide();
$( "#reportdiv" ).html("");
$.ajax({
type: "GET",
headers: { 'authtoken': getToken() },
url:'/reportservice/v1/report/'+objectid.id,
success: function(data){
if(data == null)
{
alert("That report does not exist.");
}
else
{
var retHTML = dataToTabHTML(data.config);
$("#reportdiv").html(retHTML).fadeIn(500);
$(function() {
tabs = $( "#reportdiv" ).tabs();
tabs.find( ".ui-tabs-nav" ).sortable({
axis: "x",
stop: function() {
tabs.tabs( "refresh" );
}
});
});
}
}
});
}
</script>
This works fine the first time displayreport is called. However, if the user enters another value and runs displayreport again, the "tabs" format is completely lost (the tabs are displayed as links above my sections, and clicking on a link takes you to that section further down the page).
I figured completely re-setting the reportdiv html at the beginning of the function would bring me back to original state and allow it to work normally every time. Any suggestions?
After more testing, found that destroy was the way to go. If I've set up tabs already, run the destroy, otherwise, skip the destroy (http://jsfiddle.net/scmxyras/1/) :
if(tabs!=undefined)$( "#reportdiv" ).tabs("destroy");

Jquery Opens Multiple Dialog boxes in MVC 4.0

Jquery Opens Multiple Dialog boxes in MVC 4.0
In _layout file I have this code:
<script type="text/javascript">
$(function () {
$("#tabs").tabs();
$("#dialog").dialog({
autoopen: false,
height: 600,
width: 800
});
});
</script>
and when I use an Ajax call using this:
success: function (data) {
$("#dialog").html(data);
}
it show a lot more 100 of dialog boxes and keeps opening until closed forcely,
but when I use only
success: function (data) {
alert(data);
}
it shows only 1 alert box containing data,
Please lead me to some Solution,
Try this code
<script type="text/javascript">
function show()
{
$("#dialog").dialog({
autoopen: false,
height: 600,
width: 800
});
}
</script>
success: function (data) {
$("#dialog").html(data);
show();
}

.load Scripts in JQuery dialog

Hi I'm trying to load a script to create some charts in a dialog box using JQuery.
In my view I have a partial ready and waiting that is in the dialog when I inspect it with Chrome Tools:
<div id="mydialog">
#Html.Partial("_fooChart", "Home")
</div>
I then have the dialog box that fires on click, the dialog opens but it is blank. If you inspect it with Chrome Tools you can see the elements from the partial are there. (The elements don't contain content, the function will create the content based on id's.)
Here is the dialog:
$(function () {
$('#mydialog').dialog({
autoOpen: false,
height: 800,
width: 800,
resizable: false,
open: function () {
$('#mydialog').load($('#mydialog'), function () {
fooChartLoad()
});
},
title: 'Foo Chart',
modal: true,
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
$('#my-button').click(function () {
$('#mydialog').dialog("open")
});
});
And here is the script I am trying to load:
function fooChartLoad() {
setTimeout(function () {
createFooChart();
$('#fooChartContainer').bind("kendo:skinChange", function (e) {
createFooChart();
});
}, 200);
}
Basically I'm trying to figure out why the dialog is not loading up the fooChartLoad when I call it with the open -> load function in JQuery dialog.
I had attempted to have a partial populate the dialog HTML before the .load called the scripts that would render data visuals, but .load it would appear works better when I loaded the partial and scripts at the same time as below:
open: function () {
$('#fooChartDialog').load($('#fooChartDialog').data('url'), function () {
fooChartLoad()
});

Update jquery ui dialog from another jquery ui dialog

I have a jquery dialog and from this one, i open another dialog, where user insert some data. How can I update this user data from the second dialog to the first one, without closing them?
Is this possible? Are some examples in the web?
Thanks in advance
ok so this is my script, which opens the second dialog. I open this dialog with a link, which calls a function in my mvc controller, and this returns the partial view with the datas...
<script type="text/javascript">
$(document).ready(function () {
$("#dialog2").dialog({
bgiframe: false,
autoOpen: false,
height: 200,
resizable: false,
modal: true,
buttons: {
OK: function () {
$("#dialog2 > form").submit();
$(this).dialog('close');
},
Abbrechen: function () {
$(this).dialog('close');
}
}
});
$('#changePW').click(function () {
$('#dialog1').dialog('open')
});
});
</script>
#Roysvork: then I have to but this in the buttons OK function?
As a dialog is simply an html element underneath, you can still access said element using jQuery in the usual fashion:
var dialog1 = $("#dialog1");
var dialog2 = $("#dialog2");
dialog1.dialog("show");
dialog2.dialog("show");
So in your event handler for dialog 1 you can just do :
var value = dialog2.find("#inputbox").val();
dialog2.find("#textbox").val(value) ;
etc...

Resources