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
Related
I'm trying to use Mozilla Readability stand-alone library for a personal project I am currently developing. The idea is to pass Mozilla Readability a document element and that after some parsing magic it returns the document's title, author, text, etc.
So, the first thing is dealing with how to get the HTML source of an external URL. I have dealt with that using an internal PHP file, which retrieves this external URL's source code.
After that, I call an AJAX GET to process the data returned by my PHP file. However, I am having lots of problems to convert this HTML source into an actual Javascript document element to pass to Mozilla Readability.
This is the code that I am currently using:
$('#btn_fetch').on('click', function() {
var url = 'https://www.rtl.be/info/monde/france/pierre-bellemare-s-est-eteint-a-88-ans-1025563.aspx';
$.ajax({
type: "GET",
url: 'fetchurl.php',
data: {
url: url
},
dataType: "html"
})
.done(function(data) {
var doc = document.implementation.createHTMLDocument("New Document");
// i don't know how to add "data" into "doc" element !
var article = new Readability(doc).parse();
alert(article.title);
})
.fail(function(xhr, ajaxOptions, thrownError) {
alert('Error:' . thrownError);
});
});
I just discovered it was actually very easy. The line I was missing was...
doc.body.parentElement.innerHTML = data;
it should be added here in the .done function
.done(function(data) {
var doc = document.implementation.createHTMLDocument("New Document");
// you need to add it here
doc.body.parentElement.innerHTML = data;
var article = new Readability(doc).parse();
alert(article.title);
})
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 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...
This is my website ( work in progress ) -> Link
I use this my code, written on the basis of another creator. -> Link
Ajax Code
$.ajax({
type: 'GET',
url: href,
cache: true,
}).done(function (data) {
......
// Run scripts
$data.filter('script').each(function(){
var scriptTag = document.createElement('script');
scriptTag.text = $(this).html();
document.body.appendChild(scriptTag);
});
});
The code allows you to load the page via ajax, then without refreshing the page. The problem arises when the page has to load javascript, they are not considered and therefore the script in the loaded page does not work.
If I can (if it is not edited) I'll link the site where I'm working and try to click in the first written EdoNetowork, then a link to an account in the topic and you'll see that the code is ignored.
How can I fix?
I think the problem is in updating the javascript page to load. But how can I recharge sources are loaded via javascript src?
You are using $data.filter('script') which is not returning anything, instead use find and in your function you are using $(this).html() but as script has no html inside it so it will not give you anything, instead access attr('src') and append it to your script tag
// your function
$data.filter('script').each(function(){
var scriptTag = document.createElement('script');
scriptTag.text = $(this).html(); // use $(this).attr('src')
// scriptTag.attr('src', $(this).attr('src')) // use it like this
document.body.appendChild(scriptTag);
});
you can also load javascript in your done callback in ajax call usinf jquery getScript()
$.ajax({
.. }).done(function () {
$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) { ... })
});
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