calling function from another function not working - javascript

I have 2 functions on a webpage, function A should be loaded at page generation (init), then after every 60 seconds OR when "Button1" is clicked and the Ajax Post is successful.
This is what I have so far:
<script src="http://code.jquery.com/jquery-2.0.3.js"></script>
<script>
$(function A() {
$.ajax({
url: "url",
type: "post",
datatype: "html",
data: {var1: "123"}
},
complete: function() {
setTimeout(A, 60000);
}
});
});
$(document).ready(function() {
console.log( "ready!" );
$('#Button1').click(function() {
$.ajax({
url: "url",
type: "post",
datatype: "html",
data: {var2: "123"},
success: function(data){
console.log( "Function Successful!" );
A(); //CALL FUNCTION A - NOT WORKING
},
}); //End of AJAX
});
});
</script>
Function A alone works perfectly.
When I click on Button1 I got in the console a "Function Successful" message, BUT Function A is not being triggered.
How can I run function A when Button1 is clicked and Ajax is successful?

Define your function in same scope. Currently you have defined your function A in another scope.
$(document).ready(function() {
function A() {
$.ajax({
url: "url",
type: "post",
datatype: "html",
data: {var1: "123"},
// remove this},
complete: function() {
setTimeout(A, 60000);
}
});
}
$('#Button1').click(function() {
$.ajax({
url: "url",
type: "post",
datatype: "html",
data: {var2: "123"},
success: function(data){
console.log( "Function Successful!" );
A(); //CALL FUNCTION A
},
}); //End of AJAX
})
});

To have the function running once while initiated and then use it again later you could create an anonymous function that returns itself like this:
var A = (function A() {
// do the functions stuff
return A;
})();
When you want to run it again it can be called using A():
$(document).ready(function() {
var A = (function A() {
// stuff here
return A;
})();
$('#Button1').click(function() {
$.ajax({
url: "url",
success: function(data){
A(); //CALL FUNCTION A
}
});
})
});

Related

How to write code to refresh table inside jquery-ajax success function

$(document).ready(function () {
$('#ajax1').click(function () {
var adMessagev = $('#adMessage').val();
var datastr = 'adMessage=' + adMessagev;
$.ajax({
type: "post",
data: datastr,
url: "adminchatServlet",
success: function ()
{
$('#tb1').dataTable().ajax.reload();
}
});
});
});
You can do something like this if you calling another function,
function func1() {
$.ajax({ ... }).done(func2);
}
And,
function func2(){
$.ajax({ ... });
}
Hope this helps.

setTimeout not giving the expected output

I have the following code but it doesn't seem to work properly. I cant understand why.
JS
var updateBoard = function() {
$.ajax({
type: "POST",
url: "engine/main.php",
data: {codes: 2},
success: function(response) {
console.log(response);
}
});
setTimeout(updateBoard, 1000);
};
PHP
if(isset($_POST['codes'])) {
echo "test";
}
You can try with following approach:
var updateBoard = function() {
$.ajax({
type: "POST",
url: "engine/main.php",
data: {codes: 2},
success: function(response) {
console.log(response);
setTimeout(updateBoard, 1000); //calling the function after 1 sec after we get the response
}
});
};
updateBoard(); //calling it right away
As #Smiranin said, just call setTimeout outside of the function:
var updateBoard = function(){
$.ajax({
type: "POST",
url: "engine/main.php",
data: {codes: 2},
success: function(response) {
console.log(response)
}
})
};
setTimeout(updateBoard, 1000);
Or just use setInterval instead of SetTimeout
setInterval(updateBoard, 1000);
You can try setInterval() if you want to run this in every seconds.
var updateBoard = function() {
$.ajax({
type: "POST",
url: "engine/main.php",
data: {codes: 2},
success: function(response) {
console.log(response);
}
});
};
setInterval(updateBoard, 1000);
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

React Js Call function from a function with same component

how startserver function will call searchaws info function
startserver : function(){
var self =this;
$.ajax({
type: "POST",
url: "",enter code here
data: JSON.stringify(amazonEc2ManagerBean),
contentType: "application/json",
dataType: 'json',
success: function() {
// i want to call searchawsinfo function.
self.searchawsinfo; // i want to call searchawsinfo function.
}
});
},
searchawsinfo : function(){
// it should be called from startserver function , i guess i am missing something
},
self.searchawsinfo(); will be used instead of self.searchawsinfo;
function(){
var self = this;
$.ajax({ type: "POST", url: "",enter code here
data: JSON.stringify(amazonEc2ManagerBean),
contentType: "application/json",
dataType: 'json',
success: function() {
self.searchawsinfo(); // i want to call searchawsinfo function.
}
});
},
searchawsinfo : function(){
// it should be called from startserver function
},

Call function after ajax load()

I initiate a function after an ajax load(), but the function I intimate calls upon an additional function, which isn't working. How do I initiate ajaxstuff() after load()?
function ajaxstuff(data) {
$.ajax({
type: "POST",
url: "do-it.php",
data: {data},
success: function() {
console.log('I got this far'); // this doesn't work / isn't called
}
});
}
function doit() {
$('form').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
console.log('I got this far'); // this works
ajaxstuff(formData);
}
}
$('.popup-loader').click(function() {
$(this).append('<div class="popup"></div>');
$('.popup').load('popup.php', function() {
doit(); // this works
}
});
Check for errors in your console, also, in your AJAX add an async option. set it to FALSE ("Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called"):
function ajaxstuff(data) {
$.ajax({
async: false,
type: "POST",
url: "do-it.php",
data: data,
success: function(result) {
console.log(result); //check in your console for errors
}
});
}
Syntax error in ajaxstuff function. data: {data}, , probably should be data: data,
Also when you're passing a FormData object to $.ajax, you have to specify processData: false and contentType: false
$.ajax({
type: "POST",
url: "do-it.php",
data: data,
processData: false,
contentType: false,
success: function() {
console.log('I got this far');
}
});

make another Jquery AJAX call in error case of existing AJAX call

I have the following code which work fine in case of success and error. But what I want to do is make another ajax call in case of error. to some other URL . what is the correct way of doing it. I tried calling the ajax function again but it resulted in a javascript error
this is the sample of working code.
$('#save-walkin').die('vclick').live('vclick', function(e) {
e.preventDefault();
$.mobile.showPageLoadingMsg();
$.ajax({
url: 'http://www.someurl.com',
method: 'POST',
data: $('#form-createwalkin').serialize(),
success: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
},
error: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
}
});
return false;
});
Where as what I am trying to do is something like this. but It's not working
$('#save-walkin').die('vclick').live('vclick', function(e) {
e.preventDefault();
$.mobile.showPageLoadingMsg();
$.ajax({
url: 'http://www.someurl.com',
method: 'POST',
data: $('#form-createwalkin').serialize(),
success: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
},
error: function(){
$.ajax({
url: 'http://www.someotherurl.com',
method: 'POST',
data: $('#form-createwalkin').serialize(),
success: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
},
error: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
}
}
});
return false;
});
It's just not formed correctly. It should look like this:
$('#save-walkin').die('vclick').live('vclick', function(e) {
e.preventDefault();
$.mobile.showPageLoadingMsg();
$.ajax({
url: 'http://www.someurl.com',
method: 'POST',
data: $('#form-createwalkin').serialize(),
success: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
},
error: function(){
$.ajax({
url: 'http://www.someotherurl.com',
method: 'POST',
data: $('#form-createwalkin').serialize(),
success: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
},
error: function(){
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
}
});
}
});
return false;
});
Use Deferred objects, those are objects to manipulate async calls, you can solve :
$.when($.ajax("/page1.php"), $.ajax("/page2.php"))
.then(myFunc, myFailure);
This way myFunc executes after the 2 ajax calls are made, and myFailure if either one has an error.
You can read more about it in the jquery official documentation:JQuery Deferred Object
Something like this, storing the Ajax in an object gives you a lot more flexibility, and in the error (fail) function, just call the function again with a different URL.
Will probably need some adjusting, and a counter if it's only suppose to repeat once!
runAjax('http://www.someurl.com');
funcion runAjax(url) {
var jqXHR = $.ajax({
url: url,
method: 'POST',
data: $('#form-createwalkin').serialize()
});
}
jqXHR.done(function() {
$.mobile.hidePageLoadingMsg ();
document.location.href = "queue.php";
}.fail(function() {
runAjax('http://www.someotherurl.com');
});
I think first you have to check your callback,, or error what you are getting..
may be it will help you..
$.ajax({
statusCode: {
404: function() {
alert('page not found');
}
}
});
you can also try to give
var menuId = $("ul.nav").first().attr("id");
var request = $.ajax({
url: "script.php",
type: "POST",
data: {id : menuId},
dataType: "html"
});
request.done(function(msg) {
$("#log").html( msg );
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});

Categories