I have javascript function that includes few if else statements for some reason one of the statements is not working properly.
Script:
function makePayment(reservationID) {
var expirationDate = $("#expirationDate").val();
var creditCard = $("#creditcard").val();
if (creditCard.length == 16 && expirationDate.length == 4) {
var month = "";
var year = "";
month += expirationDate.charAt(0);
month += expirationDate.charAt(1);
year += expirationDate.charAt(2);
year += expirationDate.charAt(3);
var monthInt = parseFloat(month);
var yearInt = parseFloat(year);
var currect;
if (monthInt > 0 && monthInt < 13 && yearInt > 12 && yearInt < 24) {
$.ajax({
url: "CreditAuthentication",
data: "type=reserve&creditCard=" + creditCard + "&expirationDate=" + expirationDate,
success: function(responseText) {
currect = responseText;
console.log(responseText);
}, error: function(xhr) {
alert(xhr.status);
}});
if (currect == true) {
//
$.ajax({
type: "POST",
url: "paymentMethods",
data: "type=make&reservationID=" + reservationID,
success: function(msg) {
console.log("Paymentmade");
alert("Payment made");
//alert(CCA);
document.location = "index.jsp#reservation";
}
});
}
else if(currect === "false") {
alert("Please enter valid details. 3rd");
}
//
} else {
alert("Please enter valid details. 2nd");
}
} else {
alert("Please enter valid payment information. 1st");
}
}
I have checked in FireBug and the return value from my servlet is correct and and the console.log(responseText); displays the response in console. However for some reason this part of statement is not working and not displaying the alerts:
if (currect == true) {
$.ajax({
type: "POST",
url: "paymentMethods",
data: "type=make&reservationID=" + reservationID,
success: function (msg) {
console.log("Paymentmade");
alert("Payment made");
document.location = "index.jsp#reservation";
}
});
} else if (currect === "false") {
alert("Please enter valid details. 3rd");
}
Thanks in Advance!
Please make sure currect is not null or undefined and if it is not.
make a 'currect' global so it can be accessable:
var currect; //declare it here
$.ajax({
url: "CreditAuthentication",
data: "type=reserve&creditCard=" + creditCard + "&expirationDate=" + expirationDate,
success: function(responseText) {
currect = responseText;
console.log(responseText);
}, error: function(xhr) {
alert(xhr.status);
}});
then if currect is a boolean then try:
if (currect) {
//your code
} else {
//your code
}
and if it is string:
if (currect === 'true') {
//your code
} else if(currect === 'false') {
//your code
}
You have to place the currect if/else in the success function of your ajax call.
Related
I have a function Checkdate. I want to connect this function to a save button when the user addss an event.
If the date exists, the save button shouldn't work:
$('#btnSave').click(function () {
//Validation/
if ($('#txtSubject').val().trim() == "") {
alert('Subject required');
return;
}
if ($('#txtStart').val().trim() == "") {
alert('Start date required');
return;
}
if ($('#chkIsFullDay').is(':checked') == false && $('#txtEnd').val().trim() == "") {
alert('End date required');
return;
}
else {
var startDate = moment($('#txtStart').val(), "DD/MM/YYYY HH:mm A").toDate();
var endDate = moment($('#txtEnd').val(), "DD/MM/YYYY HH:mm A").toDate();
if (startDate > endDate) {
alert('Invalid end date');
return;
}
}
SaveEvent(data);
// call function for submit data to the server
})
This is my function:
$('#btnSave').click (function () {
var StartDate = $('#txtStart').val();
$.ajax({
type: "POST",
url: "/Home/Checkdate",
data: '{StartDate: "' + StartDate + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var message = $("#message");
if (response) {
//Email available.
message.css("color", "green");
message.html(" date is not exist ");
}
else {
//Email not available.
message.css("color", "red");
message.html("date existe ");
}
}
});
});
function ClearMessage() {
$("#message").html("");
}
I hope you look at this image to understand me:
enter image description here
I'm trying to do Inventory checking with using ajax post method and return with some array value. My response is okay, but I cannot access the array value of my response. I'm using response[0] and response[1]["OptionKey"] but it doesn't show anything.
response
[6,{"OptionKey":"215,221,224"}]
javascript
function InventoryChecking(LineOptionData) {
var ItemID = $("#tiItemID").val();
var OptVal = LineOptionData;
$.ajax({
type: 'POST',
enctype: 'multipart/form-data',
url: '<?= site_url() ?>item/InventoryChecking',
data: "ItemID=" + ItemID + "&OptVal=" + OptVal + "&From=" + From,
success: function (response) {
console.log(response);
if (From === "mytray") {
$("#ItemBalance").text(response[0]);
} else {
$("#ItemBalance").text(response);
}
qty = $("#quantity").val();
if (From === "mytray" && response[0] - qty === -qty && BaseLineOptionData === response[1]["OptionKey"]) {
$("#btnAddToTray").attr("disabled", false);
} else if ((response - qty) < 0) {
// if( (response-qty)<0 ) {
if (response <= 0) {
$("#ItemBalance").text(0); //Show 0 instead of negative
}
if (ItemStockCheck == 0) {
$("#btnAddToTray").attr("disabled", true);
} else {
$("#btnAddToTray").attr("disabled", false);
}
} else {
$("#btnAddToTray").attr("disabled", false);
}
}
});
}
PHP to respond
if ($From === "mytray") {
$array = [$reserved,$CombineOptID];
echo json_encode($array);
}
Based on jwatts1980 comment, my response is in string. To fix this I need to change my response to Javascript object.
var obj = JSON.parse(response);
I m generating dynamic html with its id. You can see the below link for the dynamic generated HTML.
Dymanic Generated HTML
So for saving this, I need some suggestion on how to save it in javascript. I tried the other fields of the HTML..
function SaveNPEDetails() {
var DashboardFields = {};
if ($('#ddlFiberised').val() == '--Select--' || $('#ddlFiberised').val() == null) {
alert('Please select FIBERISED');
return false;
}
else {
DashboardFields.NPEFiberised = $('#ddlFiberised').val();
}
if ($('#txtNoFDPSite').val() == '' || $('#txtNoFDPSite').val() == null) {
alert('Please add NO. OF FDP AT SITE');
return false;
}
else {
DashboardFields.NoOfFDPatSite = $('#txtNoFDPSite').val();
}
if ($('#txtNoOfRoutesTerAtFDP').val() == '' || $('#txtNoOfRoutesTerAtFDP').val() == null) {
alert('Please add NO. OF ROUTES TERMINATED AT FDP');
return false;
}
else {
DashboardFields.NoOfRoutesTermAtFDP = $('#txtNoOfRoutesTerAtFDP').val();
}
// Need to write saving logic for dynamic generated html here.
$.ajax({
type: "POST",
url: "DashboardData.aspx/UpdateNPEData",
data: JSON.stringify({ DashboardFields: DashboardFields }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
As per our discussion you can try something like
function SaveNPEDetails() {
var data = [];
var DashboardFields = {};
if ($('#ddlFiberised').val() == '--Select--' || $('#ddlFiberised').val() == null) {
alert('Please select FIBERISED');
return false;
}
else {
DashboardFields.NPEFiberised = $('#ddlFiberised').val();
}
if ($('#txtNoFDPSite').val() == '' || $('#txtNoFDPSite').val() == null) {
alert('Please add NO. OF FDP AT SITE');
return false;
}
else {
DashboardFields.NoOfFDPatSite = $('#txtNoFDPSite').val();
}
if ($('#txtNoOfRoutesTerAtFDP').val() == '' || $('#txtNoOfRoutesTerAtFDP').val() == null) {
alert('Please add NO. OF ROUTES TERMINATED AT FDP');
return false;
}
else {
DashboardFields.NoOfRoutesTermAtFDP = $('#txtNoOfRoutesTerAtFDP').val();
}
var chs = $("#dvNPEAddData").children(".addNPEData")
for (var i = 0; i < chs.length; i++) {
var d = {};
var ch = chs[i];
var val = $(ch).find("input[name='TerRouteName']").val();
d[$(ch).find("input[name='TerRouteName']").attr("name")] = val;
val = $(ch).find("select[name='CableType']").val();
d[$(ch).find("select[name='CableType']").attr("name")] = val;
val = $(ch).find("select[name='CableSize']").val();
d[$(ch).find("select[name='CableSize']").attr("name")] = val;
val = $(ch).find("input[name='NoLiveFibre']").val();
d[$(ch).find("input[name='NoLiveFibre']").attr("name")] = val;
data.push(d);
}
var d = JSON.stringify(data);
$.ajax({
type: "POST",
url: "DashboardData.aspx/UpdateNPEData",
data: JSON.stringify({ DashboardFields: DashboardFields , myJsonXML : d}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
Using your example in the fiddle I've done the following
$('#submit').click(function() {
var DashboardFields = {},
status = true;
$.each($('input[type="text"]'), function(i, v) {
var id = $(v).attr('id');
if ($(v).val() == '') {
alert(id + ' field is empty');
status = false;
} else {
DashboardFields[id] = $(v).val();
}
});
$.each($('select'), function(i, v) {
var id = $(v).attr('id');
if ($(v).val() == '--Select--' || $(v).val() == null) {
alert(id + ' select is empty');
status = false;
} else {
DashboardFields[id] = $(v).val();
}
});
if(!status){
alert('you have empty fields');
} else {
console.log(DashboardFields); //Here should be your Ajax Call
}
});
JsFiddle
I've used your example with ID's and created a filter in order to take dynamically the fields not by ID's, I used the ID's to map the DashboardFields object but I strongly encourage to use name or other data- param and change the jQuery code after (the line with var id=$(v).attr('id'))
Hope this helps you
I want to change text to "saving ... " when a link clicked, then I use ajax, query resets to save the form. one i receive the request i need to change the text back to normal.
In Firefox the work fine, but in chrome the text get change once response received. There is a delay in changing the text.
See my code:
function submitForm(frm, action) {
var performAction = true;
var isChange = false;
document.getElementById('saveButton').innerHTML = 'processing....';
freezeWindow();
if ((document.getElementById("primaryIframe") != null) && (action == "Save")) {
var frameId = 0;
functionSaveIframes(frameId, isChange);
} else {
if (performAction == true) {
sessionStorage.setItem('singlePage', 'false');
window.open('www.google.com', '_self');
}
}
}
function functionSaveIframes (frameId,isChange) {
var iframes = {"0":"frame1","1":"frame2"};
var url = {"0":"/test/testPrimaryPostAction.do",
"1":"/test/test2PrimaryPostAction.do"};
var iframe = document.getElementById(iframes[frameId]);
var doc = iframe.contentWindow.document;
var form = doc.forms[0];
var isEdited = doc.forms[0].isEdited.value;
var formData = $(form).serializeArray();
formData.push({name: 'fwdval', value: 'Save'});
var myUrl = url[frameId];
if(isEdited == 'true'){
isChange=true;
$.ajax({
type: "POST",
async: false,
cache: false,
url: myUrl,
data: formData,
success: function(data) {
doc.forms[0].isEdited.value = "false";
frameId = frameId + 1 ;
if (frameId < 9) {
functionSaveIframes(frameId,isChange);
}else if (frameId == 9){
reloadErrors(isChange);
}
},
error: function(e){
$("#freezeFrame").css("display","none");
alert("error Saving Data in " + iframes[frameId] + "Please try again");
}
});
}
else{
frameId = frameId + 1 ;
if (frameId < 9) {
functionSaveIframes(frameId,isChange);
}
else if (frameId == 9){
reloadErrors(isChange);
}
}
}
<li><a id="saveButton" href="javascript:submitForm( document.forms[0], 'Save' );"><i class="fa fa-floppy-o" aria-hidden="true"></i> Save</a>
</li>
**In Success Function you need to change text by using .html() **
Please check the below example.
I have the following script (see below). I have two questions regarding it:
1.What does the following line mean in the context of Knockoutjs?
ko.observable(null);
2.How can I invoke a function not yet defined as in here:
that.activePollingXhr(...
Here is the full script:
$(document).ready(function() {
function ChatViewModel() {
var that = this;
that.userName = ko.observable('');
that.chatContent = ko.observable('');
that.message = ko.observable('');
that.messageIndex = ko.observable(0);
that.activePollingXhr = ko.observable(null);
var keepPolling = false;
that.joinChat = function() {
if (that.userName().trim() != '') {
keepPolling = true;
pollForMessages();
}
}
function pollForMessages() {
if (!keepPolling) {
return;
}
var form = $("#joinChatForm");
that.activePollingXhr($.ajax({url: form.attr("action"), type: "GET", data: form.serialize(), cache: false,
success: function(messages) {
console.log(messages);
for (var i = 0; i < messages.length; i++) {
that.chatContent(that.chatContent() + messages[i] + "\n");
that.messageIndex(that.messageIndex() + 1);
}
},
error: function(xhr) {
if (xhr.statusText != "abort" && xhr.status != 503) {
resetUI();
console.error("Unable to retrieve chat messages. Chat ended.");
}
},
complete: pollForMessages
}));
$('#message').focus();
}
that.postMessage = function() {
if (that.message().trim() != '') {
var form = $("#postMessageForm");
$.ajax({url: form.attr("action"), type: "POST",
data: "message=[" + that.userName() + "] " + $("#postMessageForm input[name=message]").val(),
error: function(xhr) {
console.error("Error posting chat message: status=" + xhr.status + ", statusText=" + xhr.statusText);
}
});
that.message('');
}
}
that.leaveChat = function() {
that.activePollingXhr(null);
resetUI();
this.userName('');
}
function resetUI() {
keepPolling = false;
that.activePollingXhr(null);
that.message('');
that.messageIndex(0);
that.chatContent('');
}
}
//Activate knockout.js
ko.applyBindings(new ChatViewModel());
});
ko.observable(null); creates an observable with a value of null. Nothing different than ko.observable(5);, where the value would be 5.
I see that you're using the that.activePollingXhr observable by passing it the result of an ajax call. However, this call is asynchronous and $.ajax doesn't return the data it got from the server, but rather a jquery deferred. You need to use that.activePollingXhr insude the success callback. Here's is how your code might look like:
$.ajax({url: form.attr("action"), type: "GET", data: form.serialize(), cache: false,
success: function(messages) {
console.log(messages);
for (var i = 0; i < messages.length; i++) {
that.chatContent(that.chatContent() + messages[i] + "\n");
that.messageIndex(that.messageIndex() + 1);
}
that.activePollingXhr(messages); // <-- Note where the call to activePollingXhr is
},
error: function(xhr) {
if (xhr.statusText != "abort" && xhr.status != 503) {
resetUI();
console.error("Unable to retrieve chat messages. Chat ended.");
}
},
complete: pollForMessages
});
As for the comment under your question: that.activePollingXhr is defined as that.activePollingXhr = ko.observable(null); - an observable with value of null.
That just initializes an observable with null as the initial value.
If you need to invoke a function that is an observable, just add a second set of parenthesis.
that.activePollingXhr()()