I have been banging my head up against the wall for several hours and I need help...
I want to be able to reference my JS in an external file rather than inline
#section Scripts
for an associated cshtml file.
I have tried both of the approaches below and none of them work.
#Html.RazorJSInclude("~/Scripts/Categories/Create.js");
$.getScript("~/Scripts/Categories/Create.js", function ()
{
contentCategoriesCreate();
});
The package RazorJSInclude just doesn't work as advertised. I don't see anywhere when debugging that this js file is pulled in.
No matter what I try with the jQuery getScript method, I cannot get it to resolve the url I am pointing to.
Note that with the latter, I did include a bundle in my Layout page and the Bundle.config file.
If I include the script inline, everything works fine, but I want to decouple the inline JS from my HTML.
What is the simplest way I can do this?
EDIT
I included the Url.Content as suggested which I forgot to mention that I already tried. It didn't work (see screenshot).
I also tried the Razor Syntax: #Url.Content which also did not work. See below screenshot.
I don't know how something so simple to supposedly be able to do, is turning out to be a nightmare...
Any other suggestions would be helpful....
EDIT 2
Lastly, what I have done, was to include the script inside my bundling. However, that still did not work. This time, the script loaded with no errors, but when I click on the "Create" button, the click function doesn't fire.
Here is pertinent code inside my BundleConfig.js file:
bundles.Add(new ScriptBundle("~/bundles/jsViews").Include(
"~/Scripts/Categories/Create.js",
"~/Scripts/AntiForgeryToken.js"));
Here is pertinent code inside my _Layout.js file:
#Scripts.Render("~/bundles/jsViews")
Here is the pertinent code inside my Create.cshtml file:
#section Scripts {
<script>
$(document).ready(function ()
{
if (typeof contentCreateCategory == "function")
contentCreateCategory();
});
</script>
}
Here is the pertinent code inside my external JS file:
function contentCreateCategory()
{
function contentCategoriesCreate()
{
$('#btnCategoryCreate').click(function (e)
{
var form = $('#form1');
if (form.valid())
{
createCategory();
}
return false;
});
}
}
function createCategory()
{
var category_Input = {
CategoryDescription: $('#CategoryDescription').val()
};
var Url = $("#url").val();
$.ajax({
url: Url,
data: AddAntiCSRFToken(JSON.stringify(category_Input)),
dataType: "html",
type: "POST",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
async: false,
success: function (data, status)
{
// Record added
},
error: function (data, status, xhr)
{
alert(status + '\n' + xhr + '\n' + data);
}
});
};
Finally, here is the screenshot that proves the JS is loading, but nothing happens when I click the "Create" button. Note again, that when I include the script inline within the Create.cshtml file, everything works fine. I cannot do any more than what I've done. I've given the code & screenshots. I'm hoping somebody can please let me know what I need to do to get this to work...
Related
I'm currently working on a website which should heavily rely on ajax. But I'm facing a problem which I cannot find a solution to online.
I'll now shamelessly post my (stripped) function to completely fetch a page.
function loadTemplate(name, replaceWholePage = true){
$.when( $.ajax({ url: "./templates/{0}/{0}.html".format(name), error: function() { console.error( "Could not load HTML file of template '{0}'!".format(name)); }}),
$.ajax({ url: "./templates/{0}/{0}.css".format(name), error: function() { console.error("Could not load CSS file of template '{0}'!".format(name)); }}),
$.ajax({ url: "./templates/{0}/{0}.js".format(name), error: function() { console.error("Could not load JS file of template '{0}'!".format(name)); }}) )
.then(function(html, css, js) {
var _css = "\n<style>\n" + css[0] + "\n</style>";
var _js = "\n<script>\n" + js[0] + "\n</script>";
if(replaceWholePage) {
$("#content").empty();
}
$("#content").append(html[0]);
$("#content").append(_css);
//$("#content").append(_js);
});
}
You see the line where it appends the js file is commented. But somehow the site still gets the js. When I comment that line out, my js code isn't actually twice in the document, but still gets called twice.
As Varinder stated, jQuery automatically recognised the fetched file as javascript and executed it. Setting the dataType to "text" in the call fixed it!
Thanks
I have a div element in my index.cshtml with id #myresults and i am trying to load data through jquery.load method by calling a mvc controller method. But i am not able to get the right syntax.
I am passing a custom object as a parameter as well.
var mycustomObject = {
obj1:value1,
obj2:value2,
..
}
The following does not work...(an i have tried other combinations as well..i get server not found error)
$("#myresults").load ('#Url.Action("MyActionMethod","Home")',mycustomObject);
while the following works
$("#myresults").load('/Home/MyActionMethod', mycustomObject);
While the last statement works, it works only on localhost.
Whats the right syntax to use for jquery load with Url.Action ?
#Url.Action() will always generate the correct url, so if your getting a 404, it means this code is in an external script file. Razor code is not executed in external scripts so your url would literally be the text "#Url.Action("MyActionMethod","Home")".
Options to solve this include
moving the code into the view or its layout
declaring a global variable in the view - var url =
'#Url.Action("MyActionMethod","Home")'; an in the external file use
$("#myresults").load(url, mycustomObject);
assign the url to an element as a data-* attribute, for example
<button type="button" id="loadSomething" data-url="#Url.Action("MyActionMethod","Home")">...</button>,and in
the external file
$('#loadSomething').click(function() {
var url = $(this).data('url');
$("#myresults").load(url, mycustomObject);
});
Define the div element as:
<div id="myresults" onload="loadMyData();"></div>
And make the ajax call in your method:
<script type="text/javascript">
function loadMyData() {
$.ajax({
cache: false,
url: '#Html.Raw(Url.Action(MyActionMethod","Home"))',
data: { obj1:value1, obj2:value2 },
dataType: "json",
type: 'post',
success: function (result) {
if (result.success) {
$('#myresults').html(result.data);
}
else {
alert("Failed to load data!");
}
}
});
}
</script>
I am trying to create a commenting system for my site. A script is used to show massages (or alert) when the comment is submitted. I don't have enough knowledge in js to debug and fix this problem myself so I though I would ask here till I learn more about js.
My script imports which are in the header:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js" async></script>
<script type="text/javascript" src="/js/main.js" async></script>
And my main.js script:
// Static comments
jQuery(document).ready(function ($) {
var $comments = $('.js-comments');
$('#comment-form').submit(function () {
var form = this;
$(form).addClass('submitting');
$('#comment-form-submit').html('Loading ...');
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
contentType: 'application/x-www-form-urlencoded',
success: function (data) {
$('#comment-form-submit').html('Submitted');
$('.new-comment-form .js-notice').removeClass('notice--danger').addClass('notice--success');
showAlert('<p style="color:#47bd40">Thanks for your comment! It will show on the site once it has been approved.</p>');
},
error: function (err) {
console.log(err);
$('#comment-form-submit').html('Submit Comment');
$('.new-comment-form .js-notice').removeClass('notice--success').addClass('notice--danger');
showAlert('<p style="color:#e64848">Submission failed, please fill in all the required inputs.</p>');
$(form).removeClass('submitting');
}
});
return false;
});
function showAlert(message) {
$('.new-comment-form .js-notice').removeClass('hidden');
$('.new-comment-form .js-notice-text').html(message);
}
});
My problem is, if I submit the comment, the script doesn't work, but if I waited for sometime and submitted again, it works just fine.
I am guessing it has something to do with loading the scripts and running them, I saw some similar questions here but non of the answers fixed my problem.
Async on your script tags means 'Asynchronous'.
Usually, when you load a webpage, the browser will request (if not in its updated cache already) all the files and imports that are specified in your main html. One of these things that are loaded at start up is all your script tags.
But you have async in there.
So your code is not running because it doesn't exist yet!
Remove async and it should run fine.
I've seen this question many times here with many different answers. This code stopped working when I moved from JQuery 1.5.1 to 1.9.1.
$.ajax(
{
type: 'GET',
url: MapPath($(this).attr('path')),
cache: false,
data: '{}',
dataType: 'html',
success: function (result) {
result = $.parseHTML(result);
$('#dialog').html(result);
$('#dialog').dialog('open');
}
}
});
The result contains a link to a javascript file with a src attribute. Before I upgraded the script loaded and executed after being added to the #dialog container. Now it does not. From one suggestion I tried this after the parseHTML() method:
$.getScript("/myscript.js");
That works perfectly but that's not what I want. The loading container shouldn't have to know anything about the loaded container. If the loaded container needs a script include then that script needs to run when the container is loaded.
I've tried the suggestions of finding the script elements then eval() them. But once I parseHTML() the scripts simply aren't there anymore. For why I have to use parseHTML() see my other question.
Maybe these things are related.
It's unsafe to begin with loading scripts with html due to the way the browser will handle it (it may inconsistently execute before or after the html is ready to be manipulated). Instead, parse the string so that you can load the scripts later.
$.ajax({
type: 'GET',
url: MapPath($(this).attr('path')),
cache: false,
success: function (result) {
result = result.replace(/<script/ig, '<div class="i-script"')
.replace(/<\/script/ig, '</div');
result = $.parseHTML(result);
var scripts = $(result).find('.i-script').addBack().filter('.i-script').detach();
$('#dialog').html(result);
scripts.each(function(i,script){
$.getScript($(script).attr('src'));
});
$('#dialog').dialog('open');
}
});
Obviously, the code above will only work with external scripts, you could easily modify it to also work with inline.
Why not use the load() jQuery functionality. This method also executes any Javascript that is in the content that is being loaded.
$(container).load(src, function(response, status, xhr) {
if (status == "error") {
alert(xhr.status + " | " + xhr.statusText);
}
});
I am using the following way in order to insert an external html page into my div:
$.ajax({
url: "myHTML.html",
method: 'GET',
success: function (data) {
$("#outputDiv").html(data);
},
Error: function (err) {
alert("ERROR: " + err);
}
});
which works fine,
the issue is that I would like to run some JavaScript functions that are located in the "myHTML.html" file,
Is there a way to do something like that?
Thanks (=
It's often much easier to keep scripts in the page you are loading the content into. This is especially true if you have a group of files that all use the same ajx to load, and all call the same functions. This alleviates need to change multiple files with code revisions.
$.ajax({
url: "myHTML.html",
method: 'GET',
success: function (data) {
$("#outputDiv").html(data);
/* new html exits so can run code here that affects it*/
newHtmlAdded();
},
error: function (err) {/* note typo on capital "E" fixed*/
alert("ERROR: " + err);
}
});
function newHtmlAdded(){
fixmFormStyle();
addMyValidation();
doSomethingElse();
}
Otherwise, it's important to realize that the ready event has already occurred in page being loaded into. This means any code wrapped in ready handler will fire immediately. If the code is before the html in the remote file, it will fire before the corresponding html elements exist in the DOM...and will do nothing.
Code placed after the html in the remote file will work, since the html it refers to will have already been proceessed