Javascript functions not defined error if page loaded using ajax - javascript

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.

Related

Ajax $.post with document.ready in success

Hi I am running an AJAX Post to my PHP url and when done I am returning a document.ready function with my appended jQuery page.
I want to make sure if I am doing this correctly when placing the function in the success part of my AJAX post. It will not work at the minute. Any help would be great?
function loadJobRequests() {
/ /AJAX code to submit form.
$.ajax({
type: "POST",
url: "http://localhost:8888/EduSubOct/json-data-
jobrequests.php",
data: { userEmail: localStorage.getItem("email") },
cache: false,
success: function() {
$(document).ready(function(){
        
I just need to find out if i have to pass any parameters into the function at success and then same same parameter into document.ready. Thanks
Short answer: no, you shouldn't use $(document).ready(...) here. The function you put inside that is only executed at the moment the DOM is first "readied", shortly after page load - this will be long since past by the time your script has been loaded, executed, fired an Ajax call and then returned the response (all of which needs to happen before your success callback happens).
But the very reason that $(document).ready(...) doesn't work also means that you don't need it here. The only reason it's used is to make sure that any DOM elements you refer to (typically to attach event handlers to) actually exist and the point this code is executed. Since the "ready" event has long since fired by the time the Ajax response comes in, the DOM will accurately reflect the current content of the page, and you can safely do whatever you want to manipulate it.
So whatever function you were going to put inside there, just put directly in the success callback.

$("Div").load() appending html page after completion of $(document).ready() when written inside $(document).ready()

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.

document.ready() just running one function instead of two

I'm trying to run two js functions(i'm using jquery) in the document.ready(), but only runs one. Here is my code:
$(document).ready(function() {
show_properties();
table_events();
});
the functions are written in the same js file, but only show_properties() is loaded when the website loads. I tested in the firebug console to write
table_events()
and the console tells me "undefined", but after that the function gets loaded and the ajax calls and everything inside that function starts to work.
Why is that? How can I fix this behavior?
thanks.
Here are the functions I want to run:
function table_events(){
$.ajaxSetup ({
cache: false
});
var wait = "<img src='../images/loading_red_transparent.gif' alt='loading...' style='display:block;margin-left:auto;margin-right:auto;'/>";
$('.apartamentos tr').on('click', function() {
alert("hola.")
var id_propiedad = $(this).find(".id_propiedad").html();
var nombre_propiedad = $(this).find(".nombre_propiedad").html();
//$('#property_information').hide('slow');
$("#property_information")
.html(wait)
.load('properties_info.php',{'nombre_propiedad':nombre_propiedad,'id_propiedad':id_propiedad});
//$('#property_information').show('slow');
});
}
function show_properties(){
$.ajaxSetup ({
cache: false
});
var wait = "<img src='../images/loading_red_transparent.gif' alt='loading...' style='display:block;margin-left:auto;margin-right:auto;'/>";
$('#busca_propiedades').on('click',function(){
var user_id = $('#user_list').val();
/*var data = $.ajax({
url: "properties_list.php",
type: 'POST',
data:{ 'user_id': user_id },
cache: false,
async: false
}).responseText;
});*/
$('#lista_aptos')
.html(wait)
.load('properties_list.php',{'user_id':user_id});
//alert(data);
});
}
EDIT:
after some debugging with console.log , i found out that this code is the one that's not executing when the webpage loads:
$('.apartamentos tr').on('click', function() {
alert("hola.")
var id_propiedad = $(this).find(".id_propiedad").html();
var nombre_propiedad = $(this).find(".nombre_propiedad").html();
//$('#property_information').hide('slow');
$("#property_information")
.html(wait)
.load('properties_info.php',{'nombre_propiedad':nombre_propiedad,'id_propiedad':id_propiedad});
//$('#property_information').show('slow');
});
apparently, this function() is the one that doesn't run when the webpage loads; but when I write again in the console
table_events()
THEN the code inside this function runs when I click in the tr of the table.
Are $('.apartamentos tr') elements loaded with the load call in show_properties?
If yes then the problem is due to the fact that when table_events is executed, tr elements are not yet inserted in the #lista_aptos (cause load uses ajax, that's asynchronous).
To check please add
console.log("trs count: ", $('.apartamentos tr').size());
on top of your table_events function.
To fix you should pass table_events as completetion handler to load call:
$('#lista_aptos')
.html(wait)
.load('properties_list.php',{'user_id':user_id}, table_events);
Old response
You said "...after that the function gets loaded and the ajax calls..."
Keep in mind that ajax calls are asynchronous.
If you define the table_events function inside the ajax response handler, also if you do something to put it in a scope visible from the referencing function, the attempt to call table_events may occur before the table_events definition.
or, as Raghavan says, there's an error thrown from show_properties that prevents the execution of table_events. But better if you try to debug with console.log("text") instead of alert (alert is blocking and it will hide you problems from asynchronous calls)
please, try to make a example on http://jsfiddle.net/
If the console returns "undefined" that means the function exists, but it's returning undefined as a result.
Your function needs fixing, $(document).ready() is probably fine.
Try calling table_events() at the last line in show_properties() and see if that works.
A few things to check:
Does table_events exist in the scope of $(document).ready?
Is show_properties possibly raising an error?
This may be a good case for "alert debugging":
$(document).ready(function() {
show_properties();
// You might also put an alert at the very end of show_properties.
alert('show_properties called; now calling table_events()');
table_events();
alert('table_events called; document.ready done');
});
There is probably an error in the table_events function. Try debugging using simple alert statements.

Fire a .js file with jquery click event

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.

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