Ajax request to get HTML doesn't execute scripts - javascript

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);
}
});

Related

Jquery script not running ajax GET request

I've loaded jquery but as far as I can tell my script is not running, I don't believe its an issue with my ajax request, but rather with my loading of jquery?
I'm not getting any relevant error messages and console.log is not running.
<script src = "jquery.js">
$(document).ready(function(){
console.log('why wont my script run?')
$.ajax({
type: 'GET',
url: 'https://blockchain.info/ticker',
datatype: 'json',
success: function(data) {
window.alert('success',data)
},
error: function(error) {
window.alert('error')
}
});
});
You don't use the src attribute plus a script together within a <script> tag. It's one or the other.
If you use the src attribute then it needs to reference the .js file or the CDN.
The reason your variable isn't changing is because you need to make an AJAX call to your exchange rate API. You will then need to extract that value from the HTTP response and then update your DOM.

Loading external javascript with jQuery and suppress "Synchronous XMLHttpRequest on the main thread is deprecated..."

I've been reading several posts on this topic but haven't been able to find a solution yet. I'm using jQuery to set up a simple plugin which depends on some other files as well (for example a language file). I'd like to provide an as easy as possible set up for the end user so I would like to dynamically load those javascript files. When I do this I either run into the warning Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. or I have to delay my script because the asynchronous call isn't yet completed at the point where I need the contents of the file included.
I've tried several ways to achieve this without delaying the script:
Attempt 1. By appending to the body
$('body', document).append('<script type="text/javascript" src="myfile.js"></script>');
Attempt 2 - By using $.getScript
$.ajaxSetup({ async: false });
$.getScript('myfile.js')
.done(function(script, textStatus) {
// success code... map variables
})
.fail(function(jqxhr, settings, exception) {
if( window.console ) {
console.log('error loading the file);
}
});
Attempt 3 - By using $.ajax, roughly the same as $.getScript
$.ajax({
url: 'myfile.js',
dataType: 'script',
async: false,
success: function(script, textStatus) {
// success code... map variables
}
});
Attempt 4 - using $.holdReady() but this seems ineffective since the plugin is only initiated within $(document).ready(function() { $('.myDemo').myplugin(); }.
$.holdReady( true );
$.getScript( 'myfile.js', function() {
// success code.. map variables
$.holdReady( false );
});
How should an external file be attached/included without having to delay the script and not to ensure the warning isn't fired. Is this even possible or am I asking for water to be frozen and melted at the same time?
I've now fixed it nesting ajax requests and building upon the complete-callback. I'm not sure if this is the most desireable way but with two external files (for now) it's maintainable.
There's a downside; at this moment for each instance of the plugin two files are requested. So some sort of cache-variable should also be implemented and based on if the files are loaded already they should or shouldn't be loaded the next iteration.
Other suggestions are welcome!
$.ajax({
url: 'firstfile.js',
dataType: 'script',
success: function() {
// success code.. map variables
},
complete: function() {
$.ajax({
url: 'secondfile.js',
dataType: 'script',
success: function() {
// success code.. map variables
},
complete: function() {
// call function to continue the procedure
}
})
}
});

Cannot get a reference to an external javascript file

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...

Why is my jquery ajax not working on my page and page is also refreshing

I am new in the area of jQuery/Ajax and my little test function doesn't work. And my page is also refreshingcan any one help me
<script type="text/javascript" >
$(document).ready(function() {
$("#ser_itm").change(function() {
var id=$(this).val();
var dataString = 'id='+ id;
alert(dataString);
$.ajax({
type: "POST",
url: "bar_pull.php",
data: dataString,
cache: false,
success: function(html) {
$("#tbl").html(html);
}
});
});
});
Pass the function, not the result of the function call:
$('.linkDetails').on('click', getDetailsFromServer);
Apply the same to your AJAX success callback:
success: postToPage
Also, the getDetailsFromServer() function needs to be defined before you bind it to an event. Move the function declaration before your .on('click', ...) call.
So I'm going to try and explain these points more clearly:
You cannot access C:\Users\yah\Desktop\text.txt. This is a server side path, your javascript runs on the client side. So this needs to be a path you can browse to in your browser, something like /pathinURL/text.txt. How you do this is dependant on your hosting technology, etc.
Your call backs are also wrong,
$('.linkDetails').on('click', getDetailsFromServer());
&
success: postToPage()
these will execute the function when they are hit, (well it actually binds the function result) not when the event happens. To make these work you need to remove the braces:
$('.linkDetails').on('click', getDetailsFromServer);
&
success: postToPage
this then hooks up the actual functions as function pointers and thus the actual functions will be fired when you want them to be.
so your final code will look like:
$('.linkDetails').on('click', getDetailsFromServer);
function getDetailsFromServer() {
$.ajax({
type: 'GET',
url: '/someURL/text.txt',
success: postToPage
});
}
function postToPage(data) {
$('.textDetails').text(data);
console.log(data);
}
what Arun P Johny said is right! but your code has another probloem
$('.linkDetails').on('click', getDetailsFromServer);
try above
The same origin policy implemented by browsers prevents local file system urls... if the page and the files are in same folders it might work.
See SOP for file URI for FF

How to run JavaScript functions from an external html file that is loaded into my div dynamically?

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

Categories

Resources