How to invoke a method from ajax success function? - javascript

I've a jQuery with ajax using to fetch some data from a servlet
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url:'ServiceToFetchDocType',
type:'post',
cache:false,
success: function(response){
//some data fetched from ServiceToFetchDocType
//Need to invoke another method here
}
});
</script>
Is it possible to invoke another method inside the success function and get some value?
I've very new to jQuery and ajax, any kind of help is appreciated.

$(document).ready(function() {
$.ajax({
url: 'ServiceToFetchDocType',
type: 'post',
cache: false,
success: function(response) {
/* invoke your function*/
yourFunction();
}
});
});

you can do something like this
var invokeAfterSuccess = function() {
}
var successFunction = function(response) {
/* do something here */
invokeAfterSuccess()
}
$.ajax({
url:'ServiceToFetchDocType',
type:'post',
cache:false,
success: successFunction
})
/*--------------- OR -------------*/
$.ajax({
url:'ServiceToFetchDocType',
type:'post',
cache:false
}).done(successFunction)

<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url:'ServiceToFetchDocType',
type:'post',
cache:false,
success: function(response){
Myfunction(); //this is how you can call function
}
});
Myfunction(){
alert("hiii")
}
}
</script>
// thats how it will work

[success: function (data) {
TypeOfReportDropdown.closest("form").find("div\[id$='MonitoringChemicalData'\]")\[0\].innerHTML = data;
var hours = $("#UptimeHourYear").val();
var emissions = round(parseFloat(($("#AverageMassLoadOut").val() * hours) / 1000), 1);
$("#Emissions").val(emissions);
$("#TotalEmissions").val(emissions);
$(this).delay(3000).queue(function () {
var emissieTotal = 0;
var totalHAP = 0;
$('\[data-emissie\]').each(function () {
emissieTotal += Number($(this).data('emissie'));
var hap = $(this).data('hap');
if (hap == "True") {
totalHAP += Number($(this).data('emissie'));
}
});
var emissieFinalTotal = round(emissieTotal, 3);
$('#TotalEmissionForOnlineInstruments').html(emissieFinalTotal);
var totalHAPFinal = round(totalHAP, 3);
$('#TotalHAPForOnlineInstruments').html(totalHAPFinal);
});
}][1]

Related

ajax didn't call after success another js function

I am trying to make a ajax post. I just want to learn how can i call some function after ajax success.
I want to call the following function after ajax success:
function col() {
var $container = $(".post-users-body");
$container.imagesLoaded(function() {
$container.masonry({
columnWidth: ".collectionPostWrap",
itemSelector: ".collectionPostWrap"
});
});
}
The ajax post is this:
$("body").on("click","#update_button",function() {
var updateval = $("#update").val();
var dataString = 'update=' + updateval ;
$.ajax({
type: "POST",
url: "requests/post.php",
data: dataString,
cache: false,
success: function(html) {
$(".post-users-body").prepend(html);
col();
}
});
return false;
});
So the ajax post is working fine but it is not calling the col(); function.
What i am doing wrong here. Anyone can tell me ?
ajax returns a promise object. use that and do some function chaining.
<script>
(function(){
function col(){
alert("col called");
}
$.ajax({
type:"GET",
url:"http://localhost:5850/api/someservice"}
).done(function(){
debugger;
col();
});
})()
</script>

showing loader image with submition using ajax

$(document).ready(function(){
$('#registration_form').on('submit',function(e){
/// e.preventDefault();
$("#loading").show();
var email = $('#email').val();
var checkEmail = $("#email").val().indexOf('#');
var checkEmailDot = $("#email").val().indexOf('.');
if(email == ''){
$("#email").addClass('error');
error_flag = 1;
}
if(checkEmail<3 || checkEmailDot<9){
$("#email").addClass('error');
error_flag = 1;
}
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {email: email},
success: function(res){
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if(status == 'true'){
// $('#myModal').modal('hide');
$('#message').html('');
$('#message').html(message);
$('#message').css('color',"green");
$("loading").hide();
}
else{
$('#message').html('');
$('#message').html(message);
$('#message').css('color',"red");
}
}
});
e.preventDefault();
});
});
how to use loader with ajax when message is success the load stop when message is or error loader is stop how to use loader image image in this stiuation. if submition is true loading hide if false loading also hide.
how to use loader with ajax when message is success the load stop when message is or error loader is stop how to use loader image image in this stiuation. if submition is true loading hide if false loading also hide.
You can use the always handler to do that.
Also note that, you should so the loader only if the ajax is sent, so in your case only after the validations are done it should be done.
$(document).ready(function() {
$('#registration_form').on('submit', function(e) {
/// e.preventDefault();
var email = $('#email').val();
var checkEmail = $("#email").val().indexOf('#');
var checkEmailDot = $("#email").val().indexOf('.');
if (email == '') {
$("#email").addClass('error');
error_flag = 1;
}
if (checkEmail < 3 || checkEmailDot < 9) {
$("#email").addClass('error');
error_flag = 1;
}
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
// url: "<?=base_url('controller/register')?>",
type: "POST",
datatype: "JSON",
data: {
email: email
},
beforeSend: function() {
//show it only if the request is sent
$("#loading").show();
},
success: function(res) {
var data = $.parseJSON(res);
var status = data.status;
var message = data.message;
if (status == 'true') {
// $('#myModal').modal('hide');
$('#message').html('');
$('#message').html(message);
$('#message').css('color', "green");
$("loading").hide();
} else {
$('#message').html('');
$('#message').html(message);
$('#message').css('color', "red");
}
}
}).always(function() {
//irrespective of success/error hide it
$("#loading").hide();
});
e.preventDefault();
});
});
Have a loading image like this:
<img src="loader.gif" id="loader" />
And in the script, before the AJAX call, show it:
$("#loader").fadeIn(); // You can also use `.show()`
$.ajax({
// all your AJAX stuff.
// Inside the success function.
success: function (res) {
// all other stuff.
// hide the image
$("#loader").fadeOut(); // You can also use `.hide()`
} // End success
}); // End AJAX
Solution to your Problem
You are missing # in your call:
$("loading").hide();
//-^ Add a # here.
Change it to:
$("#loading").hide();
I'd do it this way:
function loadsth(){
$('#load_dialog').show();
$.ajax({
method: "POST",
url: "?ajax=ajax_request",
data: { data:"test"},
success:function(data) {
$('#load_dialog').hide();
}
});
});
Try using jquery's ajax function beforeSend
$.ajax({
method: "POST",
url: "/url",
data: { data:"test"},
beforeSend: function() {
//SHOW YOUR LOADER
},
success:function(data) {
//HIDE YOUR LOADER
}
});
});
I hope this has given you some idea.
try this its work for u
$.ajax({
url: "<?=base_url('controller/registration_ajax')?>",
type: 'POST',
beforeSend: function(){
$("#loaderDiv").show();
},
success: function(data) {
$('#output-json-inbox').jJsonViewer(data);
$("#loaderDiv").hide();
},
error: function() {
alert("error");
}
});

loading div not working on jquery

my html:
<span id="loading"><img src="ajax-loader.gif" /> Please Wait</span>
#loading{display:none;}
my js:
var Progressajax = false;
$(function() {
$(".commentmoreview").click(function(){
if(Progressajax) return;
Progressajax = true;
var element = $(this);
var id = element.attr("id");
$('#loading').show();
var value = $('.pagecont'+id).val();
var info = 'id='+id+'&pagecont='+value;
$.ajax({
type: "POST",
url: "php-comments/php/loadmorecomments.php",
data: info,
success: function(data){
$('#loading').hide();
Progressajax = false;
value = parseInt(value)+parseInt(5);
$('.pagecont'+id).val(value);
$(data).hide().prependTo('#loadmorecomments'+id).fadeIn(1000);
//$('#loadmorecomments'+id).prepend(data);
}
});
});
});
what is wrong that loading span is not working?
thank you friends!
The best way to show loader image while making ajax calls is using Ajax Global Events
$(document).bind("ajaxSend", function(){
$("#loading").show();
}).bind("ajaxComplete", function(){
$("#loading").hide();
});
can you change
$('#loading').show();
to
$('#loading').attr("display","block");
and try to use it like this
$.ajax({
type: "POST",
url: "php-comments/php/loadmorecomments.php",
data: info,
beforeSend: function(){
$('#loading').attr("display","block");
},
success: function(data){
$('#loading').attr("display","none");
Progressajax = false;
value = parseInt(value)+parseInt(5);
$('.pagecont'+id).val(value);
$(data).hide().prependTo('#loadmorecomments'+id).fadeIn(1000);
//$('#loadmorecomments'+id).prepend(data);
}
});

Javascript status loop

Ok, simple thing in javascript that I could not solve even searching on the web. I guess I even found the right thing but could not put on the right place.
This code tells me if a stream is online or offline. But how do I do to the status and keep updating every 5 seconds?
$(function () {
$.ajax({
type: 'GET',
url: "http://xmychannelx.api.channel.livestream.com/2.0/livestatus.json?callback=?",
dataType: 'jsonp',
success: function (jsonp) {
// parse the JSON data on success
var channel = eval(jsonp);
liveChannel = channel.channel.isLive;
if (liveChannel == true) {
document.getElementById('mydiv').innerHTML = '<p style="color: #00FF00">Online!</p>';
} else {
document.getElementById('mydiv').innerHTML = '<p style="color: #C0C0C0">Offline!</p>';
}
}
});
});
Example :
var myAjaxCall = function() {
$.ajax({
type: "GET",
url: options.feedUrl,
dataType: "xml",
async:options.sync,
success: function(xml) {
// todo
}
};
var ResInterval = window.setInterval(myAjaxCall, 60000); // 60 seconds
To Stop:
window.clearInterval(ResInterval);
use set time out function
setTimeout(function(){
//your function
foo();
},1000);
Try this out:
function checkStatus() {
$.ajax({
type: 'GET',
url: "http://xmychannelx.api.channel.livestream.com/2.0/livestatus.json?callback=?",
dataType: 'jsonp',
success: function (jsonp) {
// parse the JSON data on success
var channel = eval(jsonp);
liveChannel = channel.channel.isLive;
if (liveChannel == true) {
document.getElementById('mydiv').innerHTML = '<p style="color: #00FF00">Online!</p>';
} else{
document.getElementById('mydiv').innerHTML = '<p style="color: #C0C0C0">Offline!</p>';
}
}
});
}
$(function() {
setInterval(checkStatus, 5000);
});
This calls the function checkStatus every 5000 milliseconds (5 seconds).

How Can I Do to my textbox autocomplete, works

I'm trying to do an autocomplete to my textbox, but it doesn't work. Follow my code.
$(function () {
var credenciada = '<%= credenciadaId %>';
xml_NomeCompleto = "";
var Nomes = "";
var retorno = '';
var count = 0;
var t = '';
$.ajax({
url: "../Xml/AcessoExterno.aspx?Credenciada=" + credenciada,
type: "get",
dataType: 'xml',
async: false,
success: function (data) {
$(data).find("REGISTRO").each(function () {
t = $(this).find("NOMECOMPLETOUSUARIO").text();
Nomes += ["\"" + t + "\","];
});
}
});
$("#ctl00_contentConteudo_txtNome").autocomplete({ source: Nomes });
});
The variable 't' receives all the names of my users, normally, but the autocomplete don't work.
Wait for ajax response to complete and then initialize the autocomplete because before you initialize the plugin data is not available. Also the way you are creating Nomes(source) is wrong. Declare it as an array and use push method to populate it.
Try this
var Nomes = [];
$.ajax({
url: "../Xml/AcessoExterno.aspx?Credenciada=" + credenciada,
type: "get",
dataType: 'xml',
async: false,
success: function (data) {
$(data).find("REGISTRO").each(function () {
Nomes.push($(this).find("NOMECOMPLETOUSUARIO").text());
});
$("#ctl00_contentConteudo_txtNome").autocomplete({ source: Nomes });
}
});

Categories

Resources