refer javascript array from html file - javascript

I have a question regarding ajax array. I have create two arrays in a javascript file like below.
$(document).ready(function () {
categoryarray = [];
productarray = [];
Then if I want to refer to these arrays from another javascript file with the script inside html follows the script of the javascript file that creates two arrays, but it doesn't show anything, not even console reporting error.
Below is how I refered the array in another javascript file, it didn't work.
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'my_script.js',
success: function(data) {
for(var k=0;k<categoryarray.length;k++){
if(categoryarray[k][0]!==""){
$('.tree').append('<li id="Cate_' + k + '">'+categoryarray[k][1]+'</li>');
for(var l=0;l<productarray.length;l++){
if(categoryarray[k][0]==productarray[l][2]){
$('#Cate_' + k).append('<ul id="Pro_' + l + '"></ul>');
$('#Pro_' + l).append("<li>"+productarray[l][1]+"</li>");
}
}
}
}
},
error: function() {
$('.tree').text('Failed to load the data');
console.log('Error');
}
});
});
Can anyone tell me what I have done wrong and how to fix them? Many thanks!!!

First of all place your code inside a function that you will call on some event. If you want to process your arrays after AJAX call then call that function after AJAX success. Browser render HTML from top to bottom so your script in HTML will run as soon as browser bump into script. On the other hand jQuery on ready will wait until all of the page content is fully loaded (all images, assets etc) - whole DOM, so your arrays will stay undefined.
You can fix it either by moving that code from HTML to jQuery ready function or by moving array declarations in HTML.
Anyway, if that script from HTML should run when document is ready, then it is more reasonable to move javascript code from HTML to jQuery ready function.

Related

PHP variable added to page not populated - getting undefined in Javascript function call

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.

Complete function of AJAX request not behaving as expected

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.

$("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.

JQuery - Looping a .load() inside a 'for' statement

I'm not sure if this will actually be possible, since load() is an asynchronous method, but I need some way to basically Load several little bits of pages, one at a time, get some data included in them via JavaScript, and then send that over via Ajax so I can put it on a database I made.
Basically I get this from my page, where all the links I'll be having to iterate through are located:
var digiList = $('.2u');
var link;
for(var i=0;i<digiList.length;i++){
link = "http://www.digimon-heroes.com" + $(digiList).eq(i).find('map').children().attr('href');
So far so good.
Now, I'm going to have to load each link (only a specific div of the full page, not the whole thing) into a div I have somewhere around my page, so that I can get some data via JQuery:
var contentURI= link + ' div.row:nth-child(2)';
$('#single').load('grabber.php?url='+ contentURI,function(){
///////////// And I do a bunch of JQuery stuff here, and save stuff into an object
///////////// Aaaand then I call up an ajax request.
$.ajax({
url: 'insertDigi.php',
type: 'POST',
data: {digimon: JSON.stringify(digimon)},
dataType: 'json',
success: function(msg){
console.log(msg);
}
////////This calls up a script that handles everything and makes an insert into my database.
}); //END ajax
}); //END load callback Function
} //END 'for' Statement.
alert('Inserted!');
Naturally, as would be expected, the loading takes too long, and the rest of the for statement just keeps going through, not really caring about letting the load finish up it's business, since the load is asynchronous. The alert('Inserted!'); is called before I even get the chance to load the very first page. This, in turn, means that I only get to load the stuff into my div before I can even treat it's information and send it over to my script.
So my question is: Is there some creative way to do this in such a manner that I could iterate through multiple links, load them, do my business with them, and be done with it? And if not, is there a synchronous alternative to load, that could produce roughly the same effect? I know that it would probably block up my page completely, but I'd be fine with it, since the page does not require any input from me.
Hopefully I explained everything with the necessary detail, and hopefully you guys can help me out with this. Thanks!
You probably want a recursive function, that waits for one iteration, before going to the next iteration etc.
(function recursive(i) {
var digiList = $('.2u');
var link = digiList.eq(i).find('map').children().attr('href') + ' div.row:nth-child(2)';
$.ajax({
url: 'grabber.php',
data: {
url: link
}
}).done(function(data) {
// do stuff with "data"
$.ajax({
url: 'insertDigi.php',
type: 'POST',
data: {
digimon: digimon
},
dataType: 'json'
}).done(function(msg) {
console.log(msg);
if (i < digiList.length) {
recursive(++i); // do the next one ... when this is one is done
}
});
});
})(0);
Just in case you want them to run together you can use closure to preserve each number in the loop
for (var i = 0; i < digiList.length; i++) {
(function(num) { < // num here as the argument is actually i
var link = "http://www.digimon-heroes.com" + $(digiList).eq(num).find('map').children().attr('href');
var contentURI= link + ' div.row:nth-child(2)';
$('#single').load('grabber.php?url=' + contentURI, function() {
///////////// And I do a bunch of JQuery stuff here, and save stuff into an object
///////////// Aaaand then I call up an ajax request.
$.ajax({
url: 'insertDigi.php',
type: 'POST',
data: {
digimon: JSON.stringify(digimon)
},
dataType: 'json',
success: function(msg) {
console.log(msg);
}
////////This calls up a script that handles everything and makes an insert into my database.
}); //END ajax
}); //END load callback Function
})(i);// <-- pass in the number from the loop
}
You can always use synchronous ajax, but there's no good reason for it.
If you know the number of documents you need to download (you can count them or just hardcode if it's constant), you could run some callback function on success and if everything is done, then proceed with logic that need all documents.
To make it even better you could just trigger an event (on document or any other object) when everything is downloaded (e.x. "downloads_done") and listen on this even to make what you need to make.
But all above is for case you need to do something when all is done. However I'm not sure if I understood your question correctly (just read this again).
If you want to download something -> do something with data -> download another thing -> do something again...
Then you can also use javascript waterfall (library or build your own) to make it simple and easy to use. On waterfall you define what should happen when async function is done, one by one.

Preventing script execution on ajax load pages with jQuery

I'm trying to load a page using the load() function, the problem is that javascript code on that page is being executed when loading. I use this:
$('#itemid').load('thepage.php #selector', function() {
MY CODE HERE
});
how can i prevent the javascript code from being executed and load only the HTML part that i want?
Use .get() or .post() and process what you get back. Pull the script tags out of your returned code before you append it to the page, or just pull out the code you want:
$.post('thepage.php', {
data: myData
}, function(data) {
var myHTML = $(data).not('script');
$('#itemid').html(myHTML);
});
Or:
$.post('thepage.php', {
data: myData
}, function(data) {
var myHTML = $(data).filter('#selector');
$('#itemid').html(myHTML);
});
Demo: http://jsfiddle.net/jtbowden/wpNBM/
Note: As you mentioned, using a selector with load should accomplish the same thing, as you see in the example. So, if it isn't working this way, something else is going on.
Not sure if I have understood the problem correctly, but you could remove the javascript and just have the html. I assume you want to js bindings to happen on the new page though. So when you load the new page, in the callback, you could call a function that applies the needed bindings.
function applyAfterAjax(){
$(this).find('element').click(function(){alert('clicked');});
}
$('#itemid').load('thepage.php #selector',applyAfterAjax);

Categories

Resources