Cached Dynamically loaded JS callback not working on 304 - javascript

When using $.getScrtip it does not cache your dynamically loaded js, so i have this custom one.
jQuery.loadScript = function (url, callback) {
var load = true;
//check all existing script tags in the page for the url
jQuery('script[type="text/javascript"]')
.each(function () {
return load = (url != $(this).attr('src'));
});
console.log('load is ' + load);
if (load) {
//didn't find it in the page, so load it
jQuery.ajax({
type: 'GET',
url: url,
dataType: 'script',
cache: true,
ifModified: true,
success: callback
});
} else {
//already loaded so just call the callback
if (jQuery.isFunction(callback)) {
callback.call(this);
};
};
};
it works on caching part, however it does not work when i am refreshing the page using f5 and 304 is received on next attempt to dynamically load js. i get function undefined for a function defined inside the loaded js. here is how i call this (this same code perfectly with $.getScript if replaced $.loadScript)
function getvm() {
return $.getScript("Scripts/ViewModel/cachedvm-1.0.0.js")
}
function functionthatinvokesjsload() {
$.when($.get(myUrl), getvm())
.done(function(a1, a2) {
initializeVm();
});
}
Error i am getting is initializeVm() is not defined when i get 304 on js load. it works the first time. but if i later manually do it in browser debug window it does find that function. it seems to be i am trying to invoke the js before its loaded to DOM but not sure why that is happening.

i had to use
jQuery.loadScriptNoCallBack = function (url) {
return $.ajax({
type: 'GET',
url: url,
dataType: 'script',
cache: true,
ifModified: true
});
};

Related

My ajax request is not working on first page load?

I have dynamically loaded content .task-listing. The click works because it does "show" the div. But the ajax request doesnt function properly. I get a 200 status in the console, but I get no response from the server. If I refresh the page, it works properly. Why would this occur? I cant figure it out, I have been researching for over 2 hours. When I use firefox it doesnt happen again until I close the browser...
$(document).ready(function () {
$(document).on("click", ".task-listing", function () {
var info = $(this).attr("id");
getTaskInfo(info);
$(".task-data").show();
});
});
function getTaskInfo(info) {
$.ajax({
type: "POST",
url: "/src/php/get-info-task.php",
dataType: "json",
data: "info=" + info,
success: function (response) {
alert("ok");
},
});
}

jQuery script re-starting on ajax call

I'm building a javascript widget which updates a div with html from an external domain. It also intercepts any link clicks in this div and fetches fresh data, updating the div.
Issue I'm having is that when the link callback function runs after a click the JS script is re-run in it's entirety from init().
In trying to debug it, in handleClick() if I hard-code the url the script runs once as expected e.g. url: '/page-3/', but if I access the href from the clicked link e.g. url: jQuery.attr('href') the script re-runs. Is there any way of accessing this attribute without the script starting anew?
"use strict";
(function () {
var jQuery; //noconflict reference to jquery
var serverFQDN = 'http://127.0.0.1:8000';
var container = '#my-container';
function init() {
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '3.4.1') {
...
}
function scriptLoadHandler() {
// Restore $ and window.jQuery to their previous values and store the
// new jQuery in our local jQuery variable
jQuery = window.jQuery.noConflict();
console.log('jQuery is now loaded');
main();
}
function main() {
jQuery(document).ready(function () {
jQuery('head').append('<link href="' + serverFQDN + '/static/css/cleanslate.css" rel="stylesheet" type="text/css">');
jQuery('head').append('<link href="' + serverFQDN + '/widget.css" rel="stylesheet" type="text/css">');
jQuery(container).addClass('cleanslate');
// build the initial widget
jQuery.ajax({
method: "GET",
cache: false,
url: "/page-1/",
success: function (response) {
jQuery(container).html(response);
// handle clicks
jQuery(container + ' a').click(handleClick);
}
});
});
}
function handleClick() {
console.log('Intercepted link click');
jQuery.ajax({
method: "GET",
cache: false,
url: jQuery.attr('href'),
success: function (response) {
console.log('succesfully loaded external html');
jQuery(container).html(response);
jQuery(container + ' a').click(handleClick);
}
});
// disable default click action
return false;
}
init();
})();
To access the href attribute you can use the event argument, provided by the Jquery click callback:
function handleClick(event) {
//you probably want this
event.preventDefault();
console.log('Intercepted link click');
jQuery.ajax({
method: "GET",
cache: false,
url: jQuery(event.target).attr('href'),
success: function (response) {
console.log('succesfully loaded external html');
jQuery(container).html(response);
jQuery(container + ' a').click(handleClick);
}
});
// disable default click action
return false;
}

How to work with JSONP to call back the function?

I am trying to communicate with a server using JSONP call back.
Here is my code
$('.icwsDownloadRecording').click(function(){
var id = $(this).attr('data-recordingid');
$.ajax({
type: 'GET',
url: 'http://example.com/Default2.aspx',
data: {'ID': id},
dataType: 'jsonp',
cache: false,
timeout: 40000,
crossDomain:true,
jsonp: "MyCallbackFunction",
});
});
function MyCallbackFunction(data)
{
//process data further
console.log(data);
if(!data || data.url.length < 5){
return;
}
var $preparingFileModal = $("#preparing-file-modal");
$preparingFileModal.dialog({ modal: true });
$.fileDownload( data.url, {
successCallback: function (url) {
$preparingFileModal.dialog('close');
},
failCallback: function (responseHtml, url) {
$preparingFileModal.dialog('close');
$("#error-modal").dialog({ modal: true });
}
});
return false; //this is critical to stop the click event which will trigger a normal file download!
}
The issue here is that I keep getting this message in the console
ReferenceError: MyCallbackFunction is not defined
I do have this defined as you can see in my code above
The server respond looks like this
MyCallbackFunction("{'URL': 'http:\/\/example.com:8106\/ghjgj3835396265336634646562363030303122226D616C686179656B22535353557DBE0C305645E2DE110AA1D7F8792E96A3'}");
how can I correct this issue?
EDITED
This is my code after Quentin Answer , this is my new code
$(function(){
$('.icwsDownloadRecording').click(function(){
var id = $(this).attr('data-recordingid');
$.ajax({
type: 'GET',
url: 'http://example.com/Default2.aspx',
data: {'ID': id},
dataType: 'jsonp',
timeout: 40000,
success: function(data){
//process data further
console.log(data);
if(!data || data.url.length < 5){
return;
}
var $preparingFileModal = $("#preparing-file-modal");
$preparingFileModal.dialog({ modal: true });
$.fileDownload( data.url, {
successCallback: function (url) {
$preparingFileModal.dialog('close');
},
failCallback: function (responseHtml, url) {
$preparingFileModal.dialog('close');
$("#error-modal").dialog({ modal: true });
}
});
return false; //this is critical to stop the click event which will trigger a normal file download!
}
});
});
});
Unless you have all of that code wrapped in another function, that should work.
Using a hardcoded function name is bad practise though.
Update:
$(function(){
You do have all that code wrapped in another function.
Remove this:
jsonp: "MyCallbackFunction",
Replace it with:
success: MyCallbackFunction
Or you could put an anonymous function expression there instead (as you have done in your edit)
Let jQuery generate a unique function name (which protects you from race conditions) and allow the server to use the callback query string argument to determine what function name to use.
MyCallbackFunction is in the same scope as the ajax call, so it will be available to the function (which can copy it to a suitably named global).
After you fix that, you have an additional problem:
MyCallbackFunction("{'URL':
Your response is JSON encoded in a JavaScript string, but you are trying to treat it as a JavaScript object.
Either:
Fix the server so it doesn't stringify the JSON or
Run the first argument through JSON.parse
crossDomain:true,
Remove that. It doesn't do anything here. (All it does is, when using XHR (which you aren't using) to the same origin (which you aren't targeting), suppress the custom headers that aren't typically allowed on a cross-origin request so that you can perform an HTTP redirect to a different origin).
cache: false,
That's the default for JSONP requests. Including it is pointless.
return false; //this is critical to stop the click event which will trigger a normal file download!
If you want to stop the click event, then you need to return false from the click event handler function (not the Ajax success handler).
You can't wait until the Ajax function has run and got a response before doing that. Ajax is asynchronous.

Ajax callback appending desired url to existing url

I am trying to make a ajax call back to a Drupal 7. The problem I am encountering is that the url I want to use to make the callback is appended to the current page the user is viewing. I am not sure why this is happening and am wondering if some can point out my error for me. Here is the javascript code I am using to make the call:
(function($) {
function todaysHours(context) {
var callbackFunction = window.location.host +'/' + Drupal.settings.library_hours.callbackFunction,
content = $("#todays-hours").find(".block");
nIntervId = setInterval(checkTime, 300000);
function checkTime() {
request = $.ajax({
url: callbackFunction,
dataType: "json",
type: "GET"
});
request.done(function( result ) {
content.text(result[0].data);
})
}
}
Drupal.behaviors.library_hours = {
attach: function(context) {
todaysHours(context);
}
}
})(jQuery);
The url I expect to use is http://mydomain.com/ajax/get-time but what is actually being used in the ajax call is http://mydomain.com/current-page/mydomain.com/ajax/get-time even though the callbackfunction variable is set to mydomain.com/ajax/get-time.
Why is this happening and how do I fix it? Thanks.
Problem:
Protocol is not defined in the url
Solution:
update the following part in the code
(function($) {
function todaysHours(context) {
var callbackFunction = '//'+window.location.host +'/' + Drupal.settings.library_hours.callbackFunction,
// rest code
})(jQuery);

jquery $.ajax force POST

I have an ajax function that creates a link that triggers another ajax function. For some reason the second ajax function refuses to go through POST event if I've set type: "POST"
The two functionas are below:
function HandleActivateLink(source) {
var url = source.attr('href');
window.alert(url)
$.ajax({
type: "POST",
url: url,
success: function (server_response) {
window.alert("well done")
}
});
return false;
}
function HandleDeleteLink() {
$('a.delete-link').click(function () {
var url = $(this).attr('href');
var the_link = $(this)
$.ajax({
type: "POST", // GET or POST
url: url, // the file to call
success: function (server_response) {
if (server_response.object_deleted) {
FlashMessage('#form-success', 'Link Deleted <a class="activate-link" href="' + url.replace('delete', 'activate') + '">Undo</a>');
$('a.activate-link').click(function(){
HandleActivateLink($(this));
});
the_link.parent().hide();
} else {
var form_errors = server_response.errors;
alert(form_errors)
}
}
});
return false;
});
}
You'll notice HandleDeleteLink creates a new link on success, and generates a new click event for the created link. It all works butHandleActivateLink sends the request to the server as GET. I've tried using $.post instead with no luck.
Any pointers, much appreciated.
In the second event you do not inform the client to prevent the default behaviour.
One way to do this would be to change:
$('a.activate-link').click(function(){
HandleActivateLink($(this));
});
to:
$('a.activate-link').click(function(){
return HandleActivateLink($(this));
});
(This works because HandleActiveLink already returns false.)
A nicer way to do this is to pass in the event argument to the click function and tell it to preventDefault
$('a.activate-link').click(function(e){
e.preventDefault();
HandleActivateLink($(this));
});
what is your url?
btw You can't send a cross-domain post via javascript.

Categories

Resources