jQuery $.when() .then() not working for me - javascript

$.when() .then() is not working for me, what am I doing wrong? Thanks in advance for your help. I want to make sure the form is loaded first then I want to populate a <div> inside the form to show Google's recaptcha. This is the test: It actually loads the form but the alerts are not poping up at all. I the test works I'll change the "alerts" to call the showRecaptcha function.
<script type="text/javascript">
$("document").ready(function () {
function showRecaptcha(element) {
Recaptcha.create("publick_key_here", element, {
theme: "red",
callback: Recaptcha.focus_response_field});
};
// load the form
$.get('../php/formularioDeReserva.html', function (data) {
$.when($('.subscriptionForm').html(data))
.then(function(){alert('Then')})
.fail(function(){alert( 'failed.' )});
alert('I reached this point.');
});
})
</script>
Note for Felix: My tests show that .html(data) is not done instantaneously. In the following code if I leave the alert('Load was performed.') the pause of the alert give some time so the showRecaptcha succeds. If I remove the alert nothing works.
$.get('../php/formularioDeReserva.html', function (data) {
$('.subscriptionForm').html(data);
alert('Load was performed.');
showRecaptcha('recaptcha_div');
});
Note for Guiherme: Trying what you suggested, which seems to me a good logical idea, still does not work, and I don't understand why not. In the following code the subcritionForm shows but the success, error and complete alerts do not pop up at all.
$.get('../php/formularioDeReserva.html', function (data) {
$('.subscriptionForm').html(data);
// alert('Load was performed.');
// showRecaptcha('recaptcha_div');
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
Note: When did a "view source" I realized that the Java script was included twice because one of the file was not saving properly. That explained why the alerts were popping twice.

You need to call the
$.when()
before the
$.get()
but, if it just one get request, why don't use
$.ajax({...}).success(function(data){..}).error(function(){...})...;
or
$.get({...})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
even that, I think the fail() will never be call in that case.

I gave up !!!
I decided to rename the main .html file to .php and use an php include statement instead of the .get:
<div class="subscriptionForm">
<?php include("../php/formularioDeReserva.html"); ?>
</div>
and changed the jQuery to a simple calling to show recaptcha:
$("document").ready(function () {
function showRecaptcha(element) {
Recaptcha.create("public key here", element, {
theme: "red",
callback: Recaptcha.focus_response_field});
};
showRecaptcha('recaptcha_div');
[..more here..]
});
Thanks all for your help.
Update: I have just realized that perhaps I needed to create a deferral and create a promise, but I don't really understand the concept and at the end it was easy just to use an php include.

Related

jQuery wait for a function to complete before new fires

I have two functions in jQuery that I want to fire in a specific order. The first function is an ajax function which updates a partial view. The other one is supposed to do some styling on the partial view, once the ajax function has completed - this function takes a parameter.
ajaxFunction();
stylingFunction(params);
I have tried the following:
ajaxFunction(function() {
stylingFunction(params)
});
Also, I have tried to use a callback:
ajaxFunction(stylingfunction(params));
ajaxFunction(callback)
{
//Do update
callback()
}
None of these do however work. The styling appears shortly where after it dissapears because the partial view is getting updated. Where am I going wrong here?
Both functions are written in my "parent" view.
You can use .done() and .fail() chained to the $.ajax call ...
I created a couple callback functions with psuedo-code inside the successCallback() since you said you only need to run the styling function "sometimes". You will want to test whatever condition inside that function to determine if you want to run the styling function. Hope this helps.
(function($) {
$(function() { //document.ready
$.ajax({ cache: false,
url: "/blah/vlah/lah",
data: { somedata: somedata }
})
.done(successCallback)
.fail(failCallback);
});
function successCallback(data) {
if (someCondition) {
stylingFunction(params);
}
};
function failCallback(jqXHR, status, error) {
console.log(jqXHR);
console.log(error);
console.log(status);
};
})(jQuery);
I created another gist which handles ajax event delegation, you may want to review and incorporate anything that seems helpful to your situation.
https://gist.github.com/inceptzero/a753d020648f49da90f8
I also created this gist on github for an ajax request queue which is a bit more elegant and robust.
https://gist.github.com/inceptzero/e64756f9162ca6aeeee5
Since you are using jQuery you could const ajaxFunc = callback => $.ajax({...}).done( data => callback) Also you could use async/await. You can read more about it on MDN.

Auto-refresh <div> text

This has been well answered several times, but being new to js I must be missing something basic.
My simple chat page works well, but refreshes only on manual call, and I want it to auto-refresh.
The php fetches the comment via POST, writes it to the log file (in the same directory), then writes the updated log file to the div.
<div id="show"><?php include 'LOG.txt' ; ?></div>
I adapted the following code from another post and tried it in header and in body, but it is not working.
<script type="text/javascript">
function doRefresh(){
$("#show").load("LOG.txt");
}
setInterval(function(){doRefresh()}, 5000);
</script>
What does this need?
Thank you.
Your code is mostly correct. However, you want to make sure that you only fire the function only at DOM ready, if your code is in the header. And of course you have to include jQuery.
NOTE: If you place your code just before </body> as it is, it should work.
<script src="http://code.jquery.com/jquery-3.1.1.js"></script>
<script type="text/javascript">
function doRefresh(){
$("#show").load("LOG.txt");
}
$(function() {
setInterval(doRefresh, 5000);
});
</script>
setInterval() method will continue be calling until clearInterval() method is called, or when window is closed.
setTimeout() method calls a function after a specified number of milliseconds.
I'm used to treat such cases as the example below :
function doRefresh()
{
$("#show").load("LOG.txt");
setTimeout(function() {
doRefresh();
}, 2000);
}
$(document).ready(function () {
doRefresh();
});
By calling function itself like this example, with the setTimeout() method, it will be called every 2 seconds.
See my jsfiddle version
try Via Ajax
function doRefresh(){
$.ajax({
url : "helloworld.txt",
dataType: "text",
success : function (data) {
$(".text").html(data);
}
});
setTimeout(function() {
doRefresh();
}, 2000);
}
$(document).ready(function () {
doRefresh();
});
Check console for Error.
https://stackoverflow.com/a/6470614/6079755

How to do asyncrhonous jQuery.get() before $(window).load()?

I want a SVG file to be loaded in a variable before $(window).load() will be fired.
I load the file using jQuery.get(). The problem is, that this function works asynchronously and by the time, when the SVG file is read, the $(window).load() is already invoked.
So I have following code:
var data;
$(document).ready(function () {
jQuery.get(
"my.svg",
function (_data) {
data = _data;
},
'text');
});
$(window).load( function () {
alert(data);
});
The alert will show "undefined". If it will be invoked later (after 5 seconds for example) then it will show the content of the SVG file.
Any suggestions? Thanks!
I agree that setInterval would probably be the solution you want IF you want to do stuff the hard way because you can never tell how long an AJAX request is going to take.
I would recommend restructuring your code to be more like this:
<script>
$(document).ready(function () {
//this can remain async: TRUE
jQuery.get(
"my.svg",
function (_data) {
//call function to do something to svg file
//if you are relying on the SVG to be there in order to call an action
//then why not wait for the SVG to load first and then call the action
svgAction(_data);
},
'text');
function svgAction(img_code){
//do something with img code now
}
});
</script>

Keep a javascript variable after an ajax call

I'm new in javascript and jQuery.
I'm using ajax calls to get data from my server. The fact is, I'm losing my javascript variables after the call ..
Here is what I did : the variable is define outside any function and treat in an other function.
var a = 0;
function myfunction(url){
$.ajax({
url: url,
timeout: 20000,
success: function(data){
// Do some stuff
// The a variable is now undefined
},
error: function(){
// Do some stuff
}
});
}
Everything is working fine, the only thing is that I need to keep my variables ... but it looks like it's gone ..
Does anyone know why?
Thanks
You say you're using your variable in another function (but don't show us that function). However, that function is probably running before your AJAX call is complete. This is what "asynchronous" means -- they don't take place at the same time.
To fix this, add some more code inside your success callback, where it will run only after the a variable is changed.
This works and the url does stay in scope. What you should check is if you are getting an error - this will prevent success from running (toss an alert("error"); or something similar in there to test).
I use Firebug in FireFox to help me out.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
var a = 0;
function doSomething (url){
$.ajax({
url: url,
timeout: 20000,
success: function(data){
alert(a);
},
error: function(){
// Do some stuff
}
});
}
</script>
Do it

Calling jQuery Function with Javascript Function

Having some trouble getting this to work, specifically with $.getJSON(). I want to wrap the getJSON function from jQuery in a Javascript function like so:
function reload_data() {
$.getJSON("data/source", function(data) {
$.d = data;
});
}
But when I call reload_data() it doesn't execute the jQuery function inside. Any ideas?
You're not telling us enough. I will just take a guess!
If you are calling this function, and then immediately checking $.d for the results, that is not going to work because you don't allow time for the asynchronous AJAX request to complete...
reload_data();
alert($.d); // What?! It's not displaying the updated results?!
You'll have to utilize a callback structure, like jQuery uses, in order to make it work...
reload_data(function() {
alert($.d);
});
function reload_data(func) {
$.getJSON("data/source", function(data) {
$.d = data;
//Execute the callback, now that this functions job is done
if(func)
func();
});
}
Put an Alert in side the function to know its getting called.
and a try catch around the jQuery call to see if there is an error
function reload_data() {
alert('reload_data start');
try{
$.getJSON("data/source", function(data) {
$.d = data;
});
}
catch (ex){
alert ('error in jQuery call:' + ex)
}
}
Thanks for the help everyone, but the solution was actually really simple. It was just a matter of synchronization. The page was reloading before the JSON data got reloaded, so that's why I wasn't seeing an error.

Categories