Adding this js to my page:
$("#divExample").append("<script type='text\/javascript' src='\/scripts\/test_code.js'><\/script>");
Causes a request to:
http://.../scripts/test_code.js?_=1395691742415
I need to eliminate the query string as it is preventing the js file from being cached. My best guess is that this is in some way connected to jQuery ajax, which appends the same style of querystring when doing certain types of call (e.g. jsonp).
Background on why I'm doing this: I need to push off the script load (which is actually a part of a larger js block) until after the page ready event has completed. The above is just a cut down sample which shows the same symptoms.
Currently using jQuery 1.8.3 but I really hope the answer doesn't include upgrading since that will mess with dependencies.
Set the jQuery cache global to true to prevent this.
$.ajaxSetup({
cache: true
});
Even though this appears to be config just for ajax, it affects <script> tags like you're using.
If you don't want to apply the global to all ajax requests, you can use plain Javascript (no jQuery) to do it:
var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'test.js';
document.getElementById("divExample").appendChild(s);
The third option is you can use $.ajax to import the script like so:
$.ajax({
url : 'test.js',
type : 'script',
cache : true,
success : function(){
}
});
Related
I am adding a google api script using jquery ajax, based on the language lang chosen by the user inside the app:
var src = '';
if (lang == 'en') {
src = 'https://script1.googleapis.com/script1';
} else {
src = 'https://script2.googleapis.com/script2';
}
jQuery.ajax({
url: src,
dataType: 'script',
success: function () {
},
async: true
});
Once this is added, when the user changes the language, the second script gets added to the page, and I get this error:
You have included the Google Maps API multiple times on this page.
This may cause unexpected errors.
How can I remove the old script once the language is changed? so that each time the script corresponding to the chosen language of the site is loaded?
thanks
Once a script is loaded, the objects and functions it defines are kept in memory.
The best you can do is to is to remove it globally like delete window.ga and load again your script.
and if you about the duplication of script on the dom just remove it before calling the next script.
before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>
I am using the below code in a script tag to call one URL in the background.
var request = new Ajax.Request(logoffURL, {method : 'post'});
But I am getting script error Ajax is undefined.
Do I need to include any external scripts?
That code uses Prototype. If you want to use that code, you'll need to include Prototype into your page. For example, using Google's CDN:
<script src="//ajax.googleapis.com/ajax/libs/prototype/1.7.1.0/prototype.js"></script>
Yes, you need to include some external script (jQuery, for instance) and learn how to do ajax calls there. There is no Ajax object in browser, but there is XMLHTTPRequest. But again - you must learn how to use it first. For instance - here is how you can use XMLHTTPRequest
Here's a good place to start:
http://api.jquery.com/jQuery.ajax/
As the example shows, you can do something like this:
$.ajax({
url: logoffURL,
context: document.body
}).done(function() {
alert("DONE");
});
I recommend using a CDN to reference jquery:
https://developers.google.com/speed/libraries/devguide#jquery
I have a dumb network device that has limited HTTP hosting capabilities and I'm trying to write a slightly more dynamic page to display data with. A some current process values can be found in plain-text at /temp.dat on the device, but my stone-simple jQuery script...
$(document).ready(function() {
$('#temp').load('/temp.dat');
var refreshId = setInterval(function() {
$('#temp').load('/temp.dat');
}, 2000);
$.ajaxSetup({ cache: false });
});
...seems to endlessly fail (only after the first .load on the initial page load) because the device abhors HTML query parameters. Chrome's JS console shows endless errors like the following:
GET http://192.168.1.250/temp.dat?_=1341980712854
How can I get jQuery (or pure JavaScript) to hammer away at a specific URL without attaching the HTML query (...?_=123456789)?
You should be able to add this at the top of the script
$.ajaxSetup ({
cache: true
});
when console outputs GET http://192.168.1.250/temp.dat?_=1341980712854, thats not an error, thats the log of the attempt to perform that task. When its colored red, it means that the HTTP GET of that particular address returned an error (like a 500).
I'm using jquery's ajax functions to grab a page fragment and display in a section of a page - this fragment includes html and references to external js files.
The program flow looks like this:
Main Page calls -> Fragment page which calls -> various large js files via script tags.
I've turned on the cache option on my initial ajax call so that the fragement page gets cached (no unique IDs appended to the url), however when the fragment is loaded, it appears that jquery rewrites the script urls to include a unix timestamp so that the browser downloads a new copy of the scripts every time. The scripts i'm calling are around 250kb minified and it's really hurting the user experience as the browser locks up whenever they're called. Is this a desired behaviour of jquery? Is there a way to disable the url rewrites?
Many many thanks for your help
This solution is less of a hack than Murdoch's solution:
$.ajaxPrefilter('script', function(options) {
options.cache = true;
});
See http://api.jquery.com/jQuery.ajaxPrefilter/
Looks like jQuerys's evalScript function is messing you up...
Line 543 of jQuery:
function evalScript( i, elem ) {
if ( elem.src )
jQuery.ajax({
url: elem.src,
async: false,
dataType: "script"
});
else
jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
if ( elem.parentNode )
elem.parentNode.removeChild( elem );
}
Here is the breakdown of what happens:
The Main Page's JS calls:
$.ajax({
url:"frag.htm",
type:"GET",
success:callBackFunction
})
and GETs frag.htm which contains something like this:
<html><head><script src="test.js"></script></head><body>Content</body></html>
then your callback function is called which probably looks like this:
function callBackFunction(data){
$("#ajaxContent").html(data); // <- this is the beginning of your problems...
}
When jQuery's html(data) function is called is "cleans" the HTML by removing any script tags and then calls evalScript on each one.
evalScript, as you can see, doesn't specify "cache:true" so when it goes through $.ajax cache is null. When cache is null and the dataType is "script" jQuery sets cache=false.
So, to circumvent this problem try this:
function callBackFunction(data){
var tempAJAX = $.ajax; // save the original $.ajax
$.ajax=function(s){ // wrap the old $.ajax so set cache to true...
s.cache=true;
tempAJAX(s); // call old $.ajax
}
$("#ajaxContent").html(data); // insert the HTML and download the <script>s
$.ajax = tempAJAX; // reset $.ajax to the original.
}
}
Before we insert the new HTML from "frag.htm" into the Main Page we intercept all calls to $.ajax, modify the object to include cache=true, and then after the script is loaded insert the HTML.
Let me know if you have any questions.
Force the webserver to serve the script with a expire date in the future.
If you use dataType = "script" as an option for jquery ajax the caching will be disabled by default, see http://docs.jquery.com/Ajax/jQuery.ajax#options, try set it manually to "html".
$.ajax({
type: "GET",
url: "test.js",
dataType: "html" // if not set jquery will guess what type it is and disables caching when matching "script"
});