How to use javascript variable within another javascript script? - javascript

So in an earlier part of my code, within tags I set the value of variable charge to a different link.
How do I use the value of this variable in the later javascript as 'url: charge' does not work. Do I need to write the variable differently.
'Url: chargesilver.php' works, but 'url: charge' doesn't.
<script>
function setmembershipayment(){
if (usermembershipchoice == "Silver") {
var charge = "chargesilver.php";
alert(charge);
} else if (usermembershipchoice == "Gold") {
var charge = "chargegold.php";
alert(charge);
} else if (usermembershipchoice == "Platinum") {
var charge = "chargeplatinum.php";
alert(charge);
} else {
alert("ERROR");
} // THE MISSED BRACKED!! ;)
}
</script>
.
<script>
$.ajax({
type: "POST",
url: charge,
data: form.serialize(),
success: function(response){
</script>

The easiest way is to make your function return the charge you want to use.
function getMembershipPayment(){
if (usermembershipchoice == "Silver") {
return "chargesilver.php";
} else if (usermembershipchoice == "Gold") {
return "chargegold.php";
} else if (usermembershipchoice == "Platinum") {
return "chargeplatinum.php";
} else {
alert("ERROR");
return "some default value"
} // THE MISSED BRACKED!! ;)
}
$.ajax({
type: "POST",
url: getMembershipPayment() // returns the value of charge,
data: form.serialize(),
success: function(response){}
})

Perhaps call the function from url to return the correct string value. And perhaps use a switch instead of an if/else structure as it's a little easier to read.
function setmembershipayment(usermembershipchoice) {
switch (usermembershipchoice) {
case 'Silver': return "chargesilver.php";
case 'Gold': return "chargegold.php";
case 'Platinum': return "chargeplatinum.php";
default: console.log('error'); break;
}
}
$.ajax({
type: "POST",
url: setmembershipayment(usermembershipchoice),
data: form.serialize(),
success: function(response) {
...
}
});

charge is not global.
Its scope is just within the function
Declare it outside the function
var charge = ''
function setmembershipayment(){
....
Sample
<script>
var charge = ''
function setmembershipayment(){
if (usermembershipchoice == "Silver") {
charge = "chargesilver.php";
alert(charge);
} else if (usermembershipchoice == "Gold") {
charge = "chargegold.php";
alert(charge);
} else if (usermembershipchoice == "Platinum") {
charge = "chargeplatinum.php";
alert(charge);
} else {
alert("ERROR");
} // THE MISSED BRACKED!! ;)
}
setmembershipayment()
$.ajax({
type: "POST",
url: charge, // OR Just return it from the function here and make sure there is a default value
data: form.serialize(),
success: function(response){
</script>
OR Just return it from the function and make sure there is a default value

Related

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');
}

Syntax error in ajax

I got this script from the web and I've manipulated it to fit my way but it tells me syntax error
$(document).ready(function(){
$Addr = localStorage.getItem('eaddress');
$email7 = $('#email7')
if ($Addr !== null) {
$('#email7').val($Addr);
}
if ($Addr != '') {
$.ajax({
type: "POST",
url: "/ans.php",
data: $("#form2").serialize(),
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if(result==="ok"){
window.location = 'page.html';
}
}
});
Missing a bunch of bracing:
$(document).ready(function() {
var $Addr = localStorage.getItem('eaddress');
if ($Addr) {
$('#email7').val($Addr);
$.ajax({
type: "POST",
url: "/ans.php",
data: $("#form2").serialize(),
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if (result === "ok") {
window.location = 'page.html';
}
}
});
}
});
Not absolutely required, but I also added var to local variables, simplified and combined and if test and removed a local variable not being used.
In the future, you can paste a block of code into http://jshint.com/ and it will show you where you've gone wrong. It also makes other recommendations for robust code.
Close all semicolons and braces: add });} before very last });
Result:
$(document).ready(function () {
$Addr = localStorage.getItem('eaddress');
$email7 = $('#email7')
if ($Addr != null) {
$('#email7').val($Addr);
}
if ($Addr !== '') {
$.ajax({
type: "POST",
url: "/ans.php",
data: $("#form2").serialize(),
success: function (data) {
$('#log_msg').html(data);
var result = $.trim(data);
if (result === "ok") {
window.location = 'page.html';
}
}
});
}
});

Moving data outside of the scope my jQuery AJAX call

I have a little AJAX function that asks the server whether a particular checkbox should be checked. I'd like to pass the information to a variable outside of the scope of the AJAX function. Something along the lines of:
isChecked = $.ajax({
type: "POST",
url: "/ajax/subscribe-query/",
data: "selfKey=" + commentData['selfKeyValue'],
success: function(isSubscribed){
if(isSubscribed == 'true'){
return = true;
}
else{
return = false;
}
}
})
or
var isChecked;
$.ajax({
type: "POST",
url: "/ajax/subscribe-query/",
data: "selfKey=" + commentData['selfKeyValue'],
success: function(isSubscribed){
if(isSubscribed == 'true'){
isChecked = true;
}
else{
isChecked = false;
}
}
})
Neither of those works of course. How do I do this?
var isChecked;
$.ajax({
type: "POST",
url: "/ajax/subscribe-query/",
data: "selfKey=" + commentData['selfKeyValue'],
success: function(isSubscribed){
if(isSubscribed == 'true'){
isChecked = true;
}
else{
isChecked = false;
}
}
});
alert('isChecked');
in this code even if the 'isChecked' property is set properly in the ajax success function the alert will say undefined because the ajax call is Asynchronous. It will raise the alert before the ajax success function returns. Therefore you need to do your work after the ajax success function like this. You can pass the variable to do the work after ajax success.
$.ajax({
type: "POST",
url: "/ajax/subscribe-query/",
data: "selfKey=" + commentData['selfKeyValue'],
success: function(isSubscribed){
chek(isChecked);//pass the variable here
}
});
function chek(isChecked){
if(isChecked){
$('#YourCheckbox').attr('checked','checked')
}
else{
$('#YourCheckbox').removeAttr('checked')
}
}
I'd recommend creating an object that has an isChecked property. That's safer than using a simple global variable. For example:
var inputObj = {};
$.ajax({
type: "POST",
url: "/ajax/subscribe-query/",
data: "selfKey=" + commentData['selfKeyValue'],
success: function(isSubscribed){
if(isSubscribed == 'true'){
inputObj.isChecked = true;
}
else{
inputObj.isChecked = false;
}
}
})

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