run a function after another with first data - javascript

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?

Related

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.

i am transferring control to a function written in jquery ajax

function Edit() {
var mode = 2; // 2 For Edit
var Fid = 0;
var viewName = 'MemberEditor';
var actionURL = '#Url.Action("setViewMode", "Member")';
$.ajax({
type: "POST",
data: {
Mode: mode,
lFeatureId: Fid,
ViewName: viewName
},
url: actionURL,
success: function (result) {
setViewMode(result);
}
});
}
this is the function where in i am calling setViewMode(result).
but somehow it is sot being called properly..
function setViewMode(data) {
for (keyVar in data) {
if (keyVar.search("Btn") != -1) {
jQuery('#' + keyVar).attr("disabled", data[keyVar]);
} else {
jQuery('#' + keyVar).prop("readonly", data[keyVar]);
}
}
}
The control isn't getting transferred to the loop. Can anyone help please?
I think you are getting back a JSON string. Use .$parseJSON(data) to get the contents stored.

Why trigger and click do not work in this case?

I have a piece of code that does:
$('td.unique').live('click', function () {
//function logic here
});
This works fine on I click on the td of my table. All fine!
Now I would like to be able to have the same functionality programatically in certain cases without the user actually pressing click.
I have tried:
$(document).ready(function() {
$(".clearButton").click( function () {
var username = $(this).closest('tr').find('input[type="hidden"][name="uname"]').val();
var user_id = $(this).closest('tr').find('label').val();
var input = [];
input[0] = {action:'reset', id:user_id,user:username,};
$.ajax({
url: 'updateprofile.html',
data:{'user_options':JSON.stringify(input)},
type: 'POST',
dataType: 'json',
success: function (res) {
if (res.status >= 1) {
//all ok
console.log("ALL OK");
$(this).closest('tr').find('.unique').trigger('click');
$(this).closest('tr').find('td.unique').trigger('click');
$(this).closest('tr').find('td.unique').click();
}
else {
alert('failed');
}
}
});
This button is in the same row that the td.unique is
None of these work. Why? Am I doing it wrong? Is the function that I have bind in live not taken into account when I click this way?
You need to cache the $(this) inside the ajax function.
var $this = $(this);
the $(this) inside the ajax function will not refer to the element that is clicked
$(".clearButton").click(function () {
var $this = $(this);
var username = $this.closest('tr').find('input[type="hidden"][name="uname"]').val();
var user_id = $this.closest('tr').find('label').val();
var input = [];
input[0] = {
action: 'reset',
id: user_id,
user: username,
};
$.ajax({
url: 'updateprofile.html',
data: {
'user_options': JSON.stringify(input)
},
type: 'POST',
dataType: 'json',
success: function (res) {
if (res.status >= 1) {
console.log("ALL OK");
$this.closest('tr').find('.unique').trigger('click');
$this.closest('tr').find('td.unique').trigger('click');
$this.closest('tr').find('td.unique').click();
} else {
alert('failed');
}
}
});
});

my javascript code will not proceed to delete my data from jqGrid

just want to ask regarding my javascript code. I have a function that will delete and edit a data in my jqgrid. But everytime i run my code, it will not delete and edit if I dont put an alert in some portion of the code. Why is it happening? How can i make my program run without the alert?
Below is my delete function:
function woodSpeDelData(){
var selected = $("#tblWoodSpe").jqGrid('getGridParam', 'selrow');
var woodID='';
var woodDesc='';
var codeFlag = 0;
var par_ams = {
"SessionID": $.cookie("SessionID"),
"dataType": "data"
};
//this part here will get the id of the data since my id was hidden in my jqgrid
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'getData/woodSpecie',json:JSON.stringify(par_ams)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
if (fldName == 'wood_specie_id'){
woodID = rowArrayValue;
}
if (fldName == 'wood_specie_desc'){
woodDesc = rowArrayValue;
alert($('#editWoodSpeDesc').val() +' '+ woodDesc); //program will not delete without this
if(selected == woodDesc){
codeFlag =1;
alert(woodID); //program will not delete without this
};
}
});
if (codeFlag == 1){
return false;
}
});
if (codeFlag == 1){
return false;
}
}
}
});
alert('program will not proceed without this alert');
if (codeFlag == 1) {
var datas = {
"SessionID": $.cookie("SessionID"),
"operation": "delete",
"wood_specie_id": woodID
};
alert(woodID);
alert(JSON.stringify(datas));
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'delete/woodSpecie',json:JSON.stringify(datas)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblWoodSpe').trigger('reloadGrid');
}
}
});
}
}
EDIT
My main purpose of putting an alert was just to know if my code really get the right ID of the description, and if would really go the flow of my code... But then i realized that it really wont work with it.

Categories

Resources