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.
Related
I am having a bit of trouble, and i think my syntax and structure is correct but for some reason the function is failing.
products.php page
i have this function at the bottom of the page which takes the value of $child and adds it to the page, where it gets passed to the Javascript function get_child_options:
jQuery(document).ready(function(){
get_child_options(<?=$child;?>);
});
The function get_child_options is added by my footer.php page
footer.php
function get_child_options(selected){
if(typeof selected === 'undefined'){
var selected = '';
}
var parentID = jQuery('#parent').val();
$.ajax({
url: '/admin/parsers/child_categories.php',
type: 'POST',
data: {parentID: parentID, selected: selected},
success: function (data){
jQuery('#child').html(data);
},
error: function(){alert("Something went wrong with the child options.")},
});
}
jQuery('select[name="parent"]').change(get_child_options);
The error when i load products.php is get_child_options is not declared
I have had a look online and via this forumn and i think the makeup of my function within my products.php page is correct, i just don't understand why its not recognising the function is declared within my footer.php and processing the function.
To add, i have tried this within the function on my products.php page but i got rid of the undefined error but the function didnt pass any data to my get_child_options function.
jQuery(document).ready(function(){
function getchild(child){
var child = <?=$child;?>
get_child_options(child);
}
});
If anyone can help, that would be great and i can't think of what i am doing wrong. TIA
I have reviewed How can I call PHP functions by JavaScript? and feel my situation is different to theres.
I found the issue and it was that my parsers file couldn't see my authentication file to get the function. Once i had add the correct path to the file it all worked.
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.
I am working on a jquery/ajax project. On document ready, I have the following code:
$(document).ready(function () {
$.ajax({
url: '/Main/ReturnGroups/',
dataType: "json",
success: function (data) {
$('.column').each(function (index) {
let indexVar = index;
let colID = $(this).attr("id");
for (let i = 0; i < data.length; i++) {
if ($(this).attr("id") == data[i].ColumnID) {
let thisID = $(this).attr("id");
let thisGroupID = data[i].ID;
$.ajax({
url: '/Main/GetFullGroup/',
data: { groupID: thisGroupID },
success: function (html) {
$('#' + thisID).append(html); //this html inserts a portlet (JqueryUI) based element
}
});
}
}
})
},
complete: function () {
alert($('.portlet').length); //returns 0 (leads me to believe its being run before success function
AddPageProperties(); //this function is supposed to add a bunch of classes to the elements injected in the success function but doesnt actually add the classes when its here
}
});
})
It seems to me that the contents of the complete: function is running asynchronously with the success function. From my understanding the purpose of the complete function is to run once the ajax success (or error) function is completely done.
The code is iterating all the columns and returning all the groups which have the same column id in my database, then passing the groupID to another webmethod which is then querying for all tasks and using the passed in groupID only pulling the tasks that are associated to the group, then using that data to inject a partial view to place the tasks/groups in their respective locations.
Things I've tried:
-Put the AddPageProperties() function in a button click, and after the ajax is finished, click the button. This works exactly as intended.
-use ajaxStop(). While this does work as I want for document ready, once I submit another ajax request it runs the function again, thus duplicating the code. My project uses ajax requests when elements are moved around the screen so this doesnt work.
-Try and get the details of an element to see if the html is even there in the first place when the complete: function() is run. The alert in the code snippet returns 0, which leads me to believe the HTML is not there when that alert is executed.
-using the index of the each function to determine the end of the iteration and then run the function, but again does not apply classes in the function. I tried to again do an alert to see if the elements are present, but they are not.
-set async to false, but the browser just says that its deprecated and it doesnt change any behavior
Any advice on the path towards a solution is appreciated. My goal is once all the HTML is injected, then and only then run this function and never again until page is reloaded sometime later.
I would like to stick with JQuery/ajax as my project is dependent on JQuery for Bootstrap.
Here's my issue. I have a js function that performs an $.ajax call to fetch some data from a server. When it gets that data back, I need to pass control back to the browser in order to show an update to a div.
The js function is itself within a for loop, and I need to ensure that the for loop does not advance until the js function has updated the div and allowed the Browser to display that update, at which point the for loop advances and the js function (with its ajax call) is called again, continuing until the for loop test causes the loop to end.
I've tried many different approaches - callbacks, promises etc, but to date I can't seem to get a handle on ensuring that the loop doesn't advance until the js function gets its server data, updates the div, causes the browser to display that update and fully completes.
Here's a simple stripped-down version of the function:
function myFunction (email) {
var request = $.ajax( {
url: 'getit.php',
cache: false,
async: false,
method: "post",
timeout: 1000,
data: "requesttype=getemailname&email="+encodeURIComponent(email)
});
request.done(function(response) {
$("#myDiv").html(response);
});
}
and here's part of the js that calls it:
.....
var emailscount = emails.length;
for(var i=0;i<emailscount;i++) {
myFunction (emails[i]);
}
.....
So, my issues are:
1) myFunction must allow the browser to display the updated div html - I'm not sure how to achieve that?
2) the for loop should only proceed when myFunction has received the data back from the server, updated the div html, AND allowed the browser to display that div.
At the moment, I have set the $.ajax call async flag set to "false" to stop execution until the data comes back, but how do I ensure the browser displays the new div content, and that the for loop does not proceed to call myFunction again until the previous myFunction call fully completes?
Any help you can give me would be very welcome, as right now I can't get this all to work!
Sounds like you need a recursive function, not a for loop with synchronous ajax calls
(function myFunction(i) {
$.ajax({
url: 'getit.php',
method: "post",
timeout: 1000,
data: {
requesttype : 'getemailname',
email : emails[i]
}
}).done(function(response) {
$("#myDiv").html(response);
if (emails[++i]) myFunction(i); // continue when this one is done
});
})(0);
Thanks for everyone's help! I'm making good progress (including taking care of JQuery deprecations!) but have run into a further problem. As I need to hand control back to the browser in order to show the refreshed div as I recurse, I'm calling a setTimeout as follows:
var nextBitOfWork = function () {
return myFunction(email);
};
setTimeout(nextBitOfWork, 0);
where myFunction (which recurses) now returns a promise when it's done doing it's $.ajax call.
If I simply call:
return myFunction(email);
without the setTimeout function construct above, the promise is passed through and all my promises are captured and allow me to get the array output I need and everything works great. But without the setTimeout I don't get the browser refresh. Using it as above I get the div update refresh displaying, but seem to lose the promise and so the script continues and I don't get to fill the array I use to capture values as I recurse.
Any thoughts on how to make sure the setTimeout passes on the promise?
Thanks
I've got the following code to call a json web service in a separate functions.js file.
function getMajorGroups(){
var element = $(".item-group-button");
$.ajax({
type:"GET",
url:"localhost:6458/posApplication/getAllMajorGroups",
data:"{}",
contentType:"application/json; charset=utf-8",
dataType:"json",
done:successResult(majorGroups),
fail:errorResult(error)
});
}
function successResult(majorGroups){
var mGroups = response.d;
$("#item-groups").empty();
$.each(majorGroups ,function(){
var h3 = $('h3').append(majorGroups.code);
element.append(h3);
$("#item-groups").prepend(element);
});
}
function errorResult(error){
alert("error");
}
When I run the web page and I use firebug to trace the steps I can see the script is executed. But it does not execute the success or failure code inside the ajax call. Am I doing anything wrong here?
Below is an example of the string which the service return.
{"majorGroups":[{"update":"false","hasMore":"false","status":"A","description":"Beverage","majorGroupId":"48","code":"Beverage"},{"update":"false","hasMore":"false","status":"A","description":"Laundry","majorGroupId":"51","code":"Laundry"},{"update":"false","hasMore":"false","status":"A","description":"Cigarette","majorGroupId":"50","code":"Cigarette"},{"update":"false","hasMore":"false","status":"A","description":"Food","majorGroupId":"47","code":"Food"},{"update":"false","hasMore":"false","status":"A","description":"Health Center","majorGroupId":"52","code":"Health Center"}],"failure":"false"}
$.ajax has no property named failoure. error should be used so it looks like error: errorResult
Besides that check that request is made via Network tab in Chrome dev tools or some similar tool. Check what is in the the raw response and make sure that is what you wanted. If request failed you will see way or at least have error code.
If everything is fine so far then make sure your adding DOM elements when DOM is ready so wrap your stuff with $(function(){ /* your stuff here */ })
Edit:
That's not the way done and fail should be used. jQuery ajax call returns promise.
$.ajax({
url : "..."
/* omitted */
}).done(successCallback).fail(failCallback)
where successCallback can be either function name like your defined succes function or just anonymous function like
.done(function(response){
// do stuff with response
}
I think you should carefully read jQuery documentation.
Also your $.each call is kinda broken - you skipped parameter in function provided to $.each