I am attempting to load a .js file hosted online after a jquery click event. First, am I doing this right? Will all the javascript be applied only after a link is clicked?
$(document).ready(function() {
var clickHandler ="file.js";
$('a').click(function() {
$.getScript(clickHandler, function(data, textStatus, jqxhr) {
console.log(data);
console.log(textStatus);
console.log(jqxhr.status);
});
});
Edit: I just checked the console and it is loading the file but giving me a 403 Forbidden message. Why is this happening? Do I need to have some text in my header to refer to?
EDIT 1:
Misread the jQuery code -- this part of the answer doesn't apply:
There are ways to add Javascript file to an existing document, but it isn't as simple as you are trying to do.
This discussion can explain that: How to dynamically insert a <script> tag via jQuery after page load?
The other solution is to put the contents of the Javascript into its own function, include that on the page normally and then run that function in your click handler.
Edit: Expanded answer
Lets say that you have some fairly simple code in your file.js like this:
var el = document.getElementById("fooz");
if (el) {
el.className += " example";
}
This code will, since it is not wrapped up in a function, will run (or try to run) as soon as it is loaded. It will only run once every time it is loaded.
However, if you wrap it up in a function, like this:
function colorFooz() {
var el = document.getElementById("fooz");
if (el) {
el.className += " example";
}
}
Then the code will not run until the function is called. It will load and be ready to be called later.
Error 403
The first thing to do is figure out why are getting the error 403.
At this stage, that has nothing to do with Javascript, jQuery or AJAX. Simply the problem by trying to load that Javascript file directly in your browser, by typing something like this utnil your URL:
http://example.com/file.js
Changing the URL to your website and path of course. At this point, you should still be getting the 403 error, but you can now check your server logs to see what error is written there.
I found a page that gives a guide to tracking down 403 errors here: http://www.checkupdown.com/status/E403.html
((PS: If I had to randomly guess at the reason why you are getting the 403 error, I'd say that you don't have the path file file.js correct. Depending on your structure and various includes, it may be calculating the relative path incorrectly.))
The function you pass to click() is a callback and is only executed when the element is clicked. So yes, you've got that part right.
Related
Sorry if this type of question is already been answered.
I am trying to add a page using $("Div").load() inside $(document).ready().
Page is getting loaded but it is not showing anything inside its' variables.
Steps in my code:
Page starts loading
Value come from back-end code (spring java)
Loading a specific page when values are present and show them on page.
If values are null, do not load page.
Jquery version: "2.1.3"
Below is my code:
$(document).ready(
if(condition1){
var var1= data //some json data;
$('#divId').load('url/mypage.jsp');
if(condtition == true){
myFunctionToProcessData(var1);
}
}
)
I have tried ajax call, but its not working.
After completion, I can see my page is loaded and appended in division but not showing on UI and have empty variables.
Please help.
Thank you for your responses. I could not reveal my full code, so made a snippet to give an idea about what i wanted. Issue is fixed now.
Issue was: I wanted to append a JSP on certain condition inside $(document).ready() but the working of $(document).ready() is something like, it ensures executions of methods and conditions written inside it.
Problem was:
Method "myFunctionToProcessData" and "$('#divId').load('url/mypage.jsp');" was called simultaneously , and HTML was not complete at the same time when method called and due to this, my method did not find division to set values and do other validations.
To solve this I have used below approach:
Appended html/jsp page using .load function.
used an ajax method in which i am getting data.
execution steps:
1. Code appended HTML in some time (Using setTimeout function)
2. after execution of all lines in $(document).ready(), ajax function called
3. Now myFunctionToProcessData ca find divisions to set values and proper out put shown on the UI.
code:
$(document).ready(
if(condition1){
var var1= data //some json data;
setTimeout(function() {
$('#divId').load('url/mypage.jsp');
}, 10);
if(condtition == true){
$.ajax({
type : "GET",
contentType : "application/json",
data : "&sid=" + Math.random(),
url : "url", // change to full path of file on server
success : function (data) {
myFunctionToProcessData(var1);
});
}
}
)
This is just a workaround to make sure that myFunctionToProcessData executes only after jsp appended succesfully in it.
now myFunctionToProcessData is executing at the end.
I have an issue with a tracking code that doesn't work properly since its called before a required JS script and function is loaded. Here is the situation:
Upon successful form submission (CF7 on WordPress) the following function is called right away.
function fn111Rooms(){
var email_address = document.getElementsByName("your-email")[0].value;
fnTransaction('Room booked', 'userid=' + email_address);
location.replace('http://example.com/thank-you');
}
The problem is, however, that the following script + function needs to be called beforehand to make everything work
<script type="text/javascript" src="http://www.example.com/Tracking.js"></script>
<script>fnPageHit('4ddc12d4344');</script>
This bit is placed in the section of each page but is not called again upon form submission since the form submits via AJAX (I believe that's the issue).
How can I include the script into the fn111Rooms and make sure everything is called correctly and in order. Really sorry in case that's a stupid question but JS is still confusing me from time to time.
EDIT: Would this work?
function fn111Rooms(){
// Loads the script
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", "http://www.example.com/Tracking.js")
// Calls the required function
fnPageHit('4ddc12d4344');
// Does the rest
var email_address = document.getElementsByName("your-email")[0].value;
fnTransaction('Room booked', 'userid=' + email_address);
location.replace('http://example.com/thank-you');
}
And then just call the one function when submitting the form.. ?
You could take a look at jQuery.when()
Lets say you have a function you have to execute
function yourFirstFunction(){
$.post('/somewhere');
}
And a second right after first one finishes
function yourOtherFunction() {
//stuff
}
Then you can use the following construction
$.when( yourFirstFunction() ).then(function(data) {
yourOtherFunction()
})
i.e when yourFirstFunction is done (ajax request finished) yourSecondFunction will be executed
One way to do is applying infinite loop with some interval and checking following condition
fnPageHit && fnPageHit('4ddc12d4344');
so whenevr the ile gets loaded u will get function in other cases fnPageHit will be undefined hence it will not execute and will no cause error
The functions are defined. And they are working fine. In the original page (with no ajax) the case is:
<script>
$(document).ready( function(){
callA();
});
</script>
<script>
function callA(){..}
</script>
It works fine in this case. But if the same page is called using ajax it says that
callA is not defined
in firebug console.
Am I missing anything? If it should not work then how is this working in first case?
Please help.
Edit: this is how it is called.
$.ajax({
url:selectedPortletURL,
method: "GET",
success: function(data)
{
$("#searchCriteriaDiv").html(data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert("error:" + textStatus + " - exception:" + errorThrown);
}
});
The jQuery ready event fires when the document is ready (or as soon as a function is attached to it if the document is already ready).
Since you are adding your script elements to the document after the document is ready, that is immediately.
The first script element gets parsed first. The ready handler fires. callA is not defined.
Then the second script element gets parsed. callA is defined, but too late.
You need to refactor your code. At a minimum, I'd put everything for a given page into a single script. Ideally, I'd rewrite it so that all the JS was separated out into a script file and Ajax was used to load structured data instead of HTML documents.
$(document).ready() will not fire if contained inside an AJAX response, as it is only triggered when the original document first loads.
Loading dynamic <script> tags via AJAX isn't recommended. You should try to put the code in traditional javascript files, and use a callback.
How can I fix the script below so that it will work EVERY TIME! Sometimes it works and sometimes it doesn't. Pro JQuery explains what causes this, but it doesn't talk about how to fix it. I am almost positive it has to do with the ajax ready state but I have no clue how to write it. The web shows about 99 different ways to write ajax and JQuery, its a bit overwhelming.
My goal is to create an HTML shell that can be filled with text from server based text files. For example: Let's say there is a text file on the server named AG and its contents is PF: PF-01, PF-02, PF-03, etc.. I want to pull this information and populate the HTML DOM before it is seen by the user. A was ##!#$*& golden with PHP, then found out my host has fopen() shut off. So here I am.
Thanks for you help.
JS - plantSeed.js
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init:function () {
$.ajax({
url: "./seeds/Ag.txt",
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
HTML - HEAD
<script type="text/javascript">
pageExecute.init();
</script>
HTML - BODY
<script type="text/javascript"> alert(pageExecute.fileContents); </script>
Try this:
var pageExecute = {
fileContents:"Null",
pagePrefix:"Null",
slides:"Null",
init: function () {
$.ajax({
url: "./seeds/Ag.txt",
async: false,
success: function (data){
pageExecute.fileContents = data;
}
});
}
};
Try this:
HTML:
<div id="target"></div>
JavaScript:
$(function(){
$( "#target" ).load( "pathToYourFile" );
});
In my example, the div will be filled with the file contents. Take a look at jQuery .load() function.
The "pathToYourFile" cand be any resource that contains the data you want to be loaded. Take a look at the load method documentation for more information about how to use it.
Edit: Other examples to get the value to be manipulated
Using $.get() function:
$(function(){
$.get( "pathToYourFile", function( data ) {
var resourceContent = data; // can be a global variable too...
// process the content...
});
});
Using $.ajax() function:
$(function(){
$.ajax({
url: "pathToYourFile",
async: false, // asynchronous request? (synchronous requests are discouraged...)
cache: false, // with this, you can force the browser to not make cache of the retrieved data
dataType: "text", // jQuery will infer this, but you can set explicitly
success: function( data, textStatus, jqXHR ) {
var resourceContent = data; // can be a global variable too...
// process the content...
}
});
});
It is important to note that:
$(function(){
// code...
});
Is the same as:
$(document).ready(function(){
// code
});
And normally you need to use this syntax, since you would want that the DOM is ready to execute your JavaScript code.
Here's your issue:
You've got a script tag in the body, which is asking for the AJAX data.
Even if you were asking it to write the data to your shell, and not just spout it...
...that's your #1 issue.
Here's why:
AJAX is asynchronous.
Okay, we know that already, but what does that mean?
Well, it means that it's going to go to the server and ask for the file.
The server is going to go looking, and send it back. Then your computer is going to download the contents. When the contents are 100% downloaded, they'll be available to use.
...thing is...
Your program isn't waiting for that to happen.
It's telling the server to take its time, and in the meantime it's going to keep doing what it's doing, and it's not going to think about the contents again, until it gets a call from the server.
Well, browsers are really freakin' fast when it comes to rendering HTML.
Servers are really freakin' fast at serving static (plain-text/img/css/js) files, too.
So now you're in a race.
Which will happen first?
Will the server call back with the text, or will the browser hit the script tag that asks for the file contents?
Whichever one wins on that refresh is the one that will happen.
So how do you get around that?
Callbacks.
Callbacks are a different way of thinking.
In JavaScript, you perform a callback by giving the AJAX call a function to use, when the download is complete.
It'd be like calling somebody from a work-line, and saying: dial THIS extension to reach me, when you have an answer for me.
In jQuery, you'll use a parameter called "success" in the AJAX call.
Make success : function (data) { doSomething(data); } a part of that object that you're passing into the AJAX call.
When the file downloads, as soon as it downloads, jQuery will pass the results into the success function you gave it, which will do whatever it's made to do, or call whatever functions it was made to call.
Give it a try. It sure beats racing to see which downloads first.
I recommend not to use url: "./seeds/Ag.txt",, to target a file directly. Instead, use a server side script llike PHP to open the file and return the data, either in plane format or in JSON format.
You may find a tutorial to open files here: http://www.tizag.com/phpT/fileread.php
I have code snippent which is executed on click of a link which is as below
cj_redirecturl="/HomeWork/main/load_course";
utility.xhttprw.data(cj_redirecturl,{data:courseid},function(response){
if(response){
window.location.href=base_url+"main";
///next
utility.xhttprw.data(redirecturl,{data:""},function(response){
if(response){
id=ent;
document.getElementById('content').innerHTML=response;
// Assignemnt module
//Call function from javascript/assignment.js file to display particular assignment (ent:means assignment_id) //
if(con==5)
{
get_assignment_id(ent);
}
if(con==9)
{
get_content_details(ent);
}
} //end of response
},false,false,false,'POST','html',true);
}
},false,false,false,'POST','html');
in above code window.location.href=base_url+"main";redirects the page to its respective page but this stops the execution of the code written just next to it. Now I want this code to be executed as it is been written i.e. firstly the code should take me to the respective "main" page and then code writte after that must execute and give me a required output.
Can someone guide me to achieve this?
window.location.href = base_url + "main"; <- when you load this page, call your code defined at ///next
you will have to add some parameters:
window.location.href=base_url+"main?parameter=true";
The other way would be to load the page with ajax into a div in the html.
Have a look at $.ajax() from jQuery.
please try to write
window.location.href = base_url + "main";
just before the end of if condition or use
setTimeout('window.location.href=base_url+"main"', 2000);
As already been noticed, you cant execute code after you went to another page
What you can do is to create redirector function, that will pass your function in cookie and ,redirect and then eval it on next page. (with another call to that redirector on next page)
But you should be aware of number of issues
1) Packing. It is upon you to decide how you pack cookie.
2) Encription. If you pass non-packed OR non-encrypted cookie the "bad user" can pass some malware code inside that cookie.
3) You should have VERY, VERY good reasons to do it.
This way is too complicated, hard to code, hard to maintain
Much better if you do additional server-side controls, save it somewhere and reload on next page with one more request.
You'll need to wrap the rest of the JS code inside a window.onbeforeunload callback.
See here: Intercept page exit event
You need to use the onBlur event to continue to execute js code before exit from the page.
Example:
function downloadExcel()
{
// Your code...
$('#download_excel_button').hide();
$('#download_spinner').show();
window.location.href = download_page;
window.onblur = function(event)
{
// other event code...
$('#download_spinner').hide();
$('#download_excel_button').show();
}
}