Call Function Upon Document Ready - javascript

I need to start polling a URL upon the page loading, to get a JMS response from a credit card server. I put the following together.
It works, but only if I hit the Refresh button on the browser. I want the data from the URL to load automatically when the page is first displayed, without requiring the user to Refresh.
I am missing a fundamental concept here, and would appreciate any advice on how to make it work. I have about 2 days of JavaScript experience so far.
<html>
<body>
<div id="p_results"></div>
<script type="text/javascript">
$(document).ready(function() {
function doJMSPolling() {
$.ajax({
url: "./poll",
type: "GET",
dataType: "text",
success: function(json) {
var json = $.parseJSON(json);
if (json.status === 'continue-polling' && json.msg === 'ok') {
setTimeout(function() {
doPolling();
}, 2000);
}
else if (json.status === 'stop-polling' && json.msg === 'success') {
for (key in json) {
if (key === "providerResponse") {
res = json[key];
for (reskey in res) {
$("#p_results").append(reskey + ":" + res[reskey] + "<br>");
}
}
}
} else if (json.status === 'stop-polling') {
$("#p_results").text(json.status);
}
}
});
}
});
</script>
</body>
</html>

You don't have to place the actual function definition inside your document.ready callback. The function can sit anywhere inside the <script> tags. Once you have done that, all you need to do is call the function from within the document.ready callback -
<script type="text/javascript">
$(function(){
doJMSPolling();
});
function doJMSPolling(){
...
}
</script>
Note :
$(function(){}) is shorthand for $(document).ready(function(){})

Seems to me that you're declaring your function, but not calling it. In order for the function's code to execute you'll need to add this after the function declaration within document.ready:
doJMSPolling();

Don't put your function within the document.ready, simply call it in there. Try this:
$(document).ready(function() {
doJMSPolling();
});
function doJMSPolling() {
$.ajax({
url: "./poll",
type: "GET",
dataType: "text",
success: function(json) {
var json = $.parseJSON(json);
if (json.status === 'continue-polling' && json.msg === 'ok') {
setTimeout(function() {
doPolling();
}, 2000);
}
else if (json.status === 'stop-polling' && json.msg === 'success') {
for (key in json) {
if (key === "providerResponse") {
res = json[key];
for (reskey in res) {
$("#p_results").append(reskey + ":" + res[reskey] + "<br>");
}
}
}
}
else if (json.status === 'stop-polling') {
$("#p_results").text(json.status);
}
}
});
}

Related

run a function after another with first data

I am trying to run 2 function where one is called inside the other.
I have a function and inside it I call a second function. I want to use the data from the second function in the first one.
function addLine() {
if (ContagemAntesIntegracao == '' || !ContagemAntesIntegracao) {
ContagemAntesIntegracao = 0;
}
var AfetaStock = '0';
verify_serialnumbers().complete(function (data){....
and the function that is runing inside:
function verify_serialnumbers() {
....if (ArrayErros.length > 0) {
set_errors(ArrayErros);
ArrayErros = undefined;
return;
}
...
var Link = $('#LINK').val() + '/?action=_ajax_inventory';
$.ajax({
type: 'POST',
url: Link,
dataType: 'json',
placeholder: 'Lote',
data: {
CheckSerialNumbers: '1',
CodArmazem: CodArmazem,
CodProduto: CodProduto,
CodLocalizacao: CodLocalizacao,
ArrayNumerosSerie: ArrayNumerosSerie,
}
}).done(function (response) {
if (response != 'ok')
{
set_errors(dados);
}else{
return ArrayNumerosSerie;
}
});
}
}
How can I continue inside the first one with an array that does not come from the AJAX call?

How to use defined variable out of function in javascript

I have a one signal javascript code and an ajax form, that give me a Player Id of the user in one signal,
so I want to use this code in my ajax login form and add the Player id to login form data, but i can't use a defined variable in one signal function, out of that and receive not defined message
OneSignal.push(function() {
OneSignal.getUserId(function(userId) {
var userid = userId;
});
});
var options = {
url: "{{CONFIG ajax_url}}/auth/login?hash_id=" + getHashID(),
beforeSubmit: function () {
$('#output-errors').empty();
$("#btn-submit").text("{{LANG Please wait..}}");
},
success: function (data) {
$("#btn-submit").text("{{LANG Login}}");
if (data.status == 200) {
if ($('#page').attr('data-page') != 'home' && $('#page').attr('data-page') != 'forgot' && $('#page').attr('data-page') != 'reset') {
$('#main-header').html(data.header);
$('#login_box').modal('hide');
if (Amplitude.getActiveSongMetadata().price >= 0) {
location.href = window.location.href;
} else {
ajaxRedirect();
}
} else {
location.href = window.location.href;
}
} else if (data.status == 400) {
var errros = data.errors.join("<br>");
$('#output-errors').html(errros);
}
},
// here i add the one signal id
data: {
OSid: userid
}
};
$('#login-form').ajaxForm(options);
There are a couple ways you can solve this, here's one approach:
OneSignal.push(function() {
OneSignal.getUserId(doAjax);
});
function doAjax(userId) {
var options = {
url: "{{CONFIG ajax_url}}/auth/login?hash_id=" + getHashID(),
beforeSubmit: function () {
$('#output-errors').empty()
...
}
$('#login-form').ajaxForm(options);
}
The function OneSignal.getUserId() takes a function as an argument, so my solution declares a function doAjax that will take the userId as an argument, and then we pass that function to the getUserId function.
Simplest way I suggest is:
Var userid;
OneSignal.push(function() {
OneSignal.getUserId(function(userId) {
userid = userId;
});
});

ajax loading indicator stopped in between

I am saving data on a save button click that calls ajax and passing json data to a controller method but when we save it loading starts and suddenly stop though the data is not saved.
It is not working I have tried it in all way but not working please help me on this.
<button type="button" id="saveDeleg" class="btn_reg_back btnmainsize btnautowidth btngrad btnrds btnbdr btnsavesize " aria-hidden="true" data-icon="">#Resources.Resource.Save</button>
$('#saveDeleg').click(function() {
var response = Validation();
if (!response) {
return false;
}
$("#overlay").show();
$('.loading').show();
if ($('#organName').val() == '') {
$('#validorganisation').show();
return false;
} else {
$('#validorganisation').hide();
}
//Contact name
var SubDelegation = $('#subdelegation').is(':checked');
var CopyNotification = $('#copynotification').is(':checked');
var ArrangementId = $("#ArrangementId").val();
var paramList = {
ArrangementId: ArrangementId,
ArrangementName: $('#arrangName').val(),
OrganisationName: $('#organName').val(),
OrganisationId: $('#OrganisationId').val(),
ContactName: $('#contactName').val(),
ContactId: $('#ContactId').val(),
SubDelegation: $('#subdelegation').is(':checked'),
CopyNotification: $('#copynotification').is(':checked'),
ContactType: $('#ContactType').val(),
SelectedTypeName: $("input[name$=SelectedType]:checked").val()
};
setTimeout(function() {
$.ajax({
async: false,
type: "POST",
url: '#Url.Action("SaveDelegation", "Structures")',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(paramList),
processdata: true,
success: function(result) {
//stopAnimation()
paramList = null;
if (result == 0) {
window.location.href = '../Structures/MyDelegationArrangement';
} else if (result == 1) {
window.location.href = '../Structures/CreateDelegation';
} else if (result == 2) {
window.location.href = '../Home/Error';
} else if (result == 3) {
window.location.href = '../Account/Login';
} else {
//validation message
alert('Error');
}
},
error: function() {},
complete: function() {
$("#overlay").hide();
$('.loading').hide();
}
});
}, 500);
});
The problem with the loading indicator is because you used async: false which locks up the UI. Remove that setting.
Also note that if the data is not being saved I would assume that your AJAX call is returning an error. If so, check the console to see the response code. It may also be worth putting some logic in the error callback function to give you some information on whats happened, as well as inform your users about what to do next.

if return data is null alert ajax success

How to show can alert message in the ajax return request if the return request does not contain any data !!!
i have tried in the ajax success but nothing is working!
This is my script ---
<script>
$(document).ready(function () {
$("#searchform").on('submit', function (e) {
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (returnedData) {
$("#displayResult").html($(returnedData).find("#displayResult").html());
// how can i do something where so if the return value is null alert
}
}
});
return false;
});
});
</script>
console.log(returnedData) output
Do anyone knows how i can make an alert when the return value is null !!!
how about?
success: function (returnedData) {
if(!returnedData) alert('message');
}
Try this one....
< script >
$(document).ready(function() {
$("#searchform").on('submit', function(e) {
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function(returnedData) {
if(returnedData != "") { $("#displayResult").html($(returnedData).find("#displayResult").html());
} else {
alert("Data is Null");
}
}
}
});
return false;
});
}); < /script>
success: function (returnedData) {
if(!!returnedData && returnedData != null) {
$("#displayResult").html($(returnedData).find("#displayResult").html());
} else {
alert('No data');
}
}
Or this:
success: function (returnedData) {
if(returnedData && returnedData.length) {
$("#displayResult").html($(returnedData).find("#displayResult").html());
} else {
alert('No data');
}
}
success: function (returnedData) {
$("#displayResult").html($(returnedData).find("#displayResult").html());
// check whether your returned data is null
if(returnedData == null)
{
alert("Your message");
}
}
Replace it here --
success: function (returnedData) {
if($.trim(returnedData.length))
$("#displayResult").html($(returnedData).find("#displayResult").html());
else
alert('Nothing got');
}
}
May be you would like to do this:
success: function (returnedData) {
var data = $(returnedData).find("#displayResult").html() || ""; // this won't alert but
$("#displayResult").html(data); // sets a value if that's null
}
I also wanted to do the same thingy. You can try the following code fragment. It checks your callback data`s length. Depends on it, you can trigger your success message etc. If the length of return data is zero which means NO DATA, you can trigger the message relevant to that scenario.
success: function (returnedData) {
var sizeOfData = returnedData.length; // check the size of return data, be it zero means NO DATA
if (sizeOfData != 0) {
alert('Data exists !! Success !!');
}
else {
alert('No Data !! Error !!');
}
You can try as below :
if (returnedData == 'null' || returnedData == null){
alert('I am null');
}

jquery iframe load dynamically

I am using following jquery script to load another url after successful ajax request.
$(document).ready(function() {
var $loaded = $("#siteloader").data('loaded');
if($loaded == false){
$("#siteloader").load(function (){
if(ad_id != undefined){
var req_url = base_url+'ajax/saveclick/'+ad_id+'/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function() {
$(preloader).show();
$('#adloading').remove();
},
complete: function() {
$(preloader).hide();
},
success: function(result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url+'userpanel/cpa/'+ad_id+'/');
}
});
}
else{
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
});
}
});
<iframe src="remote_url" id="siteloader"></iframe>
I don't want to run ajax again after changing src on iframe and i have also tried to stop it by $("#siteloader").data("loaded", "true");
Please suggest me a good solution for this. thanks.
If you only want to execute the "load" handler once
Simply add the line
$("#siteloader").unbind('load');
In the success callback.
If you want the "load" handler to be executed on each src change, you may do something like that :
$(document).ready(function () {
$("#siteloader").load(function () {
// Move the test in the event Handler ...
var $loaded = $("#siteloader").data('loaded');
if ($loaded == false) {
if (ad_id != undefined) {
var req_url = base_url + 'ajax/saveclick/' + ad_id + '/';
var preloader = $('#preloader');
var reqloader = $('#reqloader');
$.ajax({
url: req_url,
type: 'GET',
beforeSend: function () {
$(preloader).show();
$('#adloading').remove();
},
complete: function () {
$(preloader).hide();
},
success: function (result) {
$(reqloader).html(result);
$("#siteloader").data("loaded", "true");
$("#siteloader").attr("src", base_url + 'userpanel/cpa/' + ad_id + '/');
}
});
}
else {
$('#reqloader').html('<span class="text-danger">Invalid Approach!</span>');
}
}
});
});
Maybe your ad_id variable is not well defined / changed ...

Categories

Resources