EDIT2: Nevermind, got it working. jQuery was included again in one of the scripts called with ajax. Thanks anyway.
EDIT: This is a rephrased question. Took my a while to find where the problem was.
Calls to plugin functions (including UI effect) aren't working after I load some content with ajax.
The original question had .effect("pulsate",{},1000) call, which explains sarcastyxs answer. Now I'm trying the same thing with the countdown plugin. The same problem appears.
Here is my code. Ignore that it doesn't do much sense, it is stripped down from a larger file. By itself the code is fine. For instance, if I call fadeOut() it works, but if I use .countdown or .effect the mentioned problem appears.
var getOrderDetails= function(id){
var that = this;
$.ajax({
type: "GET",
url: "orderDetails.php",
data: {id: id},
success: function(data){
//$("#orderDetails").html(data);
$("#orderDetails").unbind().click(function(){
var status = $("#orderDetails .orderStatus").text()
acceptOrder(id, status);
});
}
});
}
var acceptOrder = function(id, status){
var that = this;
$.ajax({
type: "GET",
url: "orderStatus.php",
data: {action: 'set', id: id, status: status},
success: function(data){
var nowTime = new Date();
var countdownTime = nowTime.setMinutes(nowTime.getMinutes() + 2);
$("#waitingOrders").countdown({until: countdownTime, compact:true, format: 'MS'});
}
});
}
$(document).ready(function(){
$(".order").unbind().click(function() {
var id = $(this).find(".orderId").text();
getOrderDetails(id);
});
});
When I comment the $("#orderDetails").html(data) line (like in code), the countdown timer appears inside the orderDetails div.
When I uncomment the line, I get an countdown is not a function error. Looked at the dom in firebug, and really in first case I can see that the selector has the .countdown function, and in the second scenario it does not.
What am I missing here?
Someone please help, I have been stuck on this for a few days.
Tried to wrap the ajax success functions with another function and pass it this as context, but it doesn't help. Same thing
You seem to be missing some core functions from jquery-ui. You can download a custom jquery-ui library from the jQuery site.
You basically want to select Effects core and whatever other effect you want to use on the site. The effects core is not part of the default jQuery ui library for some reason.
Related
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.
Good day, all,
Long-time listener, first-time poster...
I have a client who has been promised a seemingly very complex bit of functionality. They want to load the contents of 3 separate pages into one, after a visitor to their site successfully logs in to their account. They want this to happen without a page refresh. Ajax is the solution. I am not, however, experienced with Ajax.
I'm having trouble figuring out how to tell when a $.get command (using jQuery's Ajax commands) has finished loading its content. My approach is to, once the login has been successful, to go and fetch the 3 separate pages, load their XHTML content into variables, and redraw the pages. Below you'll see my pseudo-code. I use "XXItemXX" to stand-in for actual paths. Each resulting page that I'm trying to pull in has a div with class "content" surrounding the data I want to retrieve. The XHTML looks like this:
<html>
<head>
<title>Page Name</title>
</head>
<body>
<div id="header">...</div>
<div class="content">
.
.
.
</div>
<div id="footer">...</div>
</body>
</html>
The jQuery code I've built follows. I'm able to get the form submitted and even get the content back from the various .get commands. The problem is, I can't seem to daisy-chain things as I normally would. I am struggling to figure out how to only fire the jQuery commands to draw the page once all 3 have been successfully retrieved. I'm afraid my biggest stumbling point is how to articulate this when searching with Google to see how others have dealt with this problem. I'm not sure exactly how to describe what I'm trying to accomplish in 10 words or less or in a fashion that will actually return the information I need.
Can anyone help with this? I'm afraid I have too little time and too much to learn.
<script type="text/javascript">
$('XXLoginFormXX').submit(function () {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
beforeSend: function() {
$('<div class="loading">Loading...</div>').insertBefore('XXLoginFormXX').css('position','absolute');
},
success: function(data) {
// On successful login, draw page.
$('.loading').fadeOut('slow');
var dr_editProfileXHTML, dr_accountOrderListXHTML, dr_wishListsXHTML;
$.get('XXPathToEditProfilePageXX', function(data1){
var dr_editProfileXHTML = $('div.content', data1);
});
$.get('XXPathToAccountOrderListPageXX', function(data2){
var dr_accountOrderListXHTML = $('div.content',data2);
});
$.get('XXPathToWishListsPageXX', function(data3){
var dr_wishListsXHTML = $('div.content',data3);
});
$('div.content').fadeOut(function(){
$(this).html(dr_editProfileXHTML);
$('XXEditProfileXHTMLXX').before(dr_accountOrderListXHTML);
$('XXEditProfileXHTMLXX').before(dr_wishListsXHTML);
}).fadeIn();
}
});
return false;
});
</script>
Thank you very much for your time, help, and consideration.
Yours,
Sylvan012
If your problem is to wait that all 3 requests have returned, then:
store the results in variables scoped a bit higher so that each of the callbacks can access them
add a variable drawing in the same scope
in each of the callbacks, check if all 3 variables are non-null and drawing is false
if that's the case, then set drawing to true, and do the work
After working on this with people's generous help, I believe I've gotten it. All my thanks to Dave Briand who taught me about .when and .then.
Following is the pseudo-code I came up with. It seems to be working! Sure there's a lot of clean-up to do, but all three of the pages are now being pulled-in! Whoot!
What do you think of my solution?
<script type="text/javascript">
$('XXLoginFormXX').submit(function () {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
beforeSend: function() {
$('<div class="loading">Loading...</div>').insertBefore('XXLoginFormXX').css('position','absolute');
},
success: function(data) {
// On successful login, draw page.
var Page01XHTML;
var Page02XHTML;
var Page03XHTML;
$.when(
$.get('XXPathToEditProfilePageXX', function(data1){
var Page02XHTML = $('div.content', data1);
}),
$.get('XXPathToAccountOrderListPageXX', function(data2){
var Page03XHTML = $('div.content',data2);
}),
$.get('XXPathToWishListsPageXX', function(data3){
var Page01XHTML = $('div.content',data3);
})
).then(function(Page02XHTML,Page03XHTML,Page01XHTML){
$('.loading').fadeOut('slow');
$('div.content').fadeOut(function(){
$(this).attr('id','MyAccount').html(' ' + Page01XHTML + Page03XHTML + Page02XHTML + ' ').parents('body').find('.content').each(function(){
dr_thisID = $(this).attr('id');
if (dr_thisID != 'MyAccount') {
$(this).appendTo($('div#MyAccount'));
}
}).parents('div#MyAccount').children().each(function(){
dr_thisClass = $(this).attr('class');
if (dr_thisClass != 'content') {
$(this).remove();
}
});
}).fadeIn();
});
}
});
return false;
});
</script>
I recently started learning javascript, and I'm currently trying to make a small script to automate a login procedure by filling the user name/password fields, and then clicking the 'Submit'-button.
My code is as follows:
window.open("");
document.getElementById('ctl00_Username').value = "XXXX";
document.getElementById('ctl00_Password').value="XXXX";
document.getElementById('ctl00_ButtonLogin').click();
If I run it once, the site is opened but no text fields are filled.
If I run the code twice (when the site is already opened) the login is successful.
I tried putting "console.log" after "window.open", but for some reason that never seems to get called.
What might I be doing wrong?
Edit: Removed unnecessary code. I am also no longer sure that the document-object actually points to the newly opened window. Calls to "console.log" and "alert" don't seem to do anything, either.
Is it possible to get the correct document-object from the window?
Is it even possible to use "window.open" and then access the new document-object?
Help would be greatly appreciated!
A reference to the window is returned from the window.open call, you can use it to modify the window.
win=window.open(...);
win.document.doYourThing
You also probably need to wait until the document is ready (aka loaded). Using jquery below
$(win.document).ready(function() {
//the document is loaded by here, this is probably where you should do your stuff.
});
1.Pass your values as query string. Example: www.test.com?username=bro&password=bro.
2.On the other page paste the below code.
$(function () {
$(document).ready(function () {
var amount = $('money').val();
var from = "INR";
var to = "SGD";
$.ajax({ type: "POST",
url: "WebService.asmx/CurrencyConversion",
data: "{amount:" + amount + ",fromCurrency:'" + from + "',toCurrency:'" + to + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var money = $(".money").val();
$(".money").replace(money, data.d);
}
});
});
});
3.Now paste this code too.
var uname = getUrlVars()["username"];
var psw = getUrlVars()["password"];
4.You will be having values in the above variables.Enjoy doing whatever you want.
I want take some data from server and write it to global array in JavaScript. Then in document ready I want to use this array to create some new elements (options). I should have global array with this data, because after first load client can modify user interface using this data.
$(document).ready(function () {
UseAjaxQueryForFillGlobalArray();
MakingInterfaceUsingGlobalArray();
});
But I have strange behavior, when I debug page, I can see that method MakingInterfaceUsingGlobalArray working first, and just after I get data via AJAX with method UseAjaxQueryForFillGlobalArray and I don't have new interface(html options) with loaded data.
If I do like this:
UseAjaxQueryForFillGlobalArray();
$(document).ready(function () {
MakingInterfaceUsingGlobalArray();
});
Then in Firefox working fine, but in another web-browsers incorrect in first load (for example go to this page by link). But if I refreshing by F5, I have correct user interface which loaded via AJAX to global JS array.
How to fix it? Maybe I using totally incorrect way?
Added after comments:
This is my ajax function:
function UseAjaxQueryForFillGlobalArray(){
var curUserId = '<%= Master.CurrentUserDetails.Id %>';
var curLocale = '<%= Master.CurrentLocale %>';
$.ajax({
type: "POST",
url: "/segment.aspx/GetArrayForCF",
data: '{"userId":"' + curUserId + '","curLocale":"' + curLocale + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//here is I doing parse my string from server and fill arrays.
}
});
}
I think that the problem is that you don't know exactly when the first function returns, since it'a asynchronous. So you should use the array in the callback only
function UseAjaxQueryForFillGlobalArray() {
// make the call
$.post(url, data, function() {
// let's be sure that the dom is ready
$(document).ready(function () {
// use the array
MakingInterfaceUsingGlobalArray();
}
}
}();// invoke the function
It's like reviving this post from the dead, but I had the same problem today, jQuery version greater than 1.6 has this ability:
https://api.jquery.com/jquery.holdready/
And I've used it like this:
$.holdReady(true);
var remoteJSONContent = null;
$.getJSON("http://www.example.com/remote.json", function(data) {
remoteJSONContent = data;
$.holdReady(false);
});
$(document).ready(function(){
console.log(remoteJSONContent);
});
Without using holdReady, I was getting null, after, I got the content.
For anyone still searching the answer for this.
My users keep complaining that a link does not show up for them. For me, I have tested this on several browsers and it works for me.
What should happen is that a process is started via AJAX using JQuery and once that is done I keep checking with the server via AJAX how much of the process has been done and once the process is complete I show them a link. But a lot of users tell me that it shows them the link and it quickly disappears back to showing 100.0%!
I can't see how I can fix this and I was hoping you guys could help me write something fool proof so that the link is always shown!
Here is the code concerned (its been shortened).
var startTime;
var continueTime;
var done = false;
function convertNow(validURL){
startTime = setTimeout('getStatus();', 6000);
$.ajax({
type: "GET",
url: "main.php",
data: 'url=' + validURL + '&filename=' + fileNameTxt,
success: function(msg){
done = true;
$("#loading").hide("slow");
$("#done").html("LINK SHOWN HERE");
}//function
});//ajax
}//function convertNow
function getStatus()
{
if(done==false){
$.ajax({
type: "POST",
url: "fileReader.php",
data: 'textFile=' + fileNameTxt,
success: function(respomse){
textFileResponse = respomse.split(" ");
$("#done").html("PROGRESS SHOWN HERE IN PERCENTAGES");
}
});//ajax
continueTime = setTimeout('getStatus();', 3000);
}
}
Thanks all
P.S. I have this question before and was given an idea of using a conditional in the function but that didn't work when it should have!!
UPDATE
I have some of my users what OS and browsers they are using and they usually say a Mac Os and firefox or safari. Not sure if that help with the solution.
The behaviour described by the users suggests that the success callback of your getStatus function is called after the one in convertNow. You should test done variable in this callback
function getStatus(){
if(done==false){
$.ajax({
type: "POST",
url: "fileReader.php",
data: 'textFile=' + fileNameTxt,
success: function(respomse){
// FIX : Already done, just ignore this callback
if (done) return;
textFileResponse = respomse.split(" ");
$("#done").html("PROGRESS SHOWN HERE IN PERCENTAGES");
// BONUS : call getStatus only when previous ajax call is finished
continueTime = setTimeout('getStatus();', 3000);
}
});//ajax
}
}
EDIT : This solution should prevent the bug from appearing most of the time, but there is still a chance. The only way to be sure is to remove the callback from convertNow and let the one in getStatus set the link when the processing is done (don't forget to allow only one call to getStatus at a time, see "BONUS" modification above).
If done is never set back to false then the reported behavior would be expected upon the second call to convertNow.
Since the ajax call in convertNow uses GET instead of POST, it is possible that a browser is returning a cached result whenever parameters are identical to a previous call.