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);
Related
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 display data stored in ch ! But my problem is that ch is displayed before the data is stored !
I think this is an Asynchronous Problems! How can I solve this problem.
When I try to get length of ch, I get always 0. Even if I store data statically in ch, I get the length 0.
I think this is an Asynchronous Problems! How can I solve this problem.
function RechercheFiltrée() {
var nom = document.getElementById('nompre').value;
var matricule = document.getElementById('matcle').value;
$.ajax({
url: "myWebServiceURL",
type: "GET",
dataType: "xml",
success: function(xml) {
var stock = [];
$(xml).find('Population').each(function() {
var table = document.getElementById("myTable");
$(this).find("directories").each(function()
{
dossier = $(this).attr('dossier');
stock.push(dossier);
});
});
var ch = [];
for (var i = 0; i < stock.length; i++) {
$.ajax({
url: "/mySecondWebServiceURL" + stock[i],
type: "GET",
dataType: "xml",
success: function(xml) {
var NMPRES = "";
var jsonObj = JSON.parse(xml2json(xml, ""));
var nom = jsonObj.SubmitResponse.occurrences.occurrence.filter(x => x["#datasection"] === "TS")[0].data.filter(x => x.item === "NMPRES")[0].value;
var matcle = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0].data.filter(x => x.item === "MATCLE")[0].value;
var dossier = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0]["#dossier"];
ch.push({
"nom": nom,
"matcle": matcle,
"dossier": dossier
});
if ($('#population').val() != null && firstIter == false) {
}
},
error: function(request, error) {
console.log('error Connexion : ' + error + ' request Connexion : ' + request);
}
});
}
var txt = "";
var firstIter = true;
for (var key in ch) {
if (ch[key].matcle === matricule) {
txt += "<option value='" + ch[key].dossier + "'" + firstSelect(firstIter) + ">" + ch[key].nom + "</option>";
firstIter = false;
}
}
$('#population').html(txt)
},
error: function(request, error) {
console.log('error Connexion : ' + error + ' request Connexion : ' + request);
}
});
}
The problem is that you are not waiting for the second service to respond.
It should be something like this:
const deferreds = stock.map((stockItem) => {
//... your logic with ch.push here
return $.ajax({
// your call to the second service
});
});
$.when(...deferreds).then(() => {
// your code
// for (var key in ch) {
});
The approach I'd rather take is to break the code down and use Promises. You really should take your time to learn Promises. It's a JavaScript standard and what jQuery uses under the hood.
function RechercheFiltrée() {
var nom = document.getElementById('nompre').value;
var matricule = document.getElementById('matcle').value;
return $.ajax({
url: "myWebServiceURL",
type: "GET",
dataType: "xml"
});
}
function getStockArray(xml) {
var stocks = [];
$(xml).find('Population').each(function() {
var table = document.getElementById("myTable");
$(this).find("directories").each(function() {
{
dossier = $(this).attr('dossier');
stocks.push(dossier);
});
});
});
return stocks;
}
function getStocks(stocks) {
return Promise.all(stocks.map(fetchStock));
}
function fetchStock (stock) {
return $.ajax({
url: "/mySecondWebServiceURL" + stock,
type: "GET",
dataType: "xml"
})
.then(formatStockInfo)
}
function formatStockInfo (xml) {
var NMPRES = "";
var jsonObj = JSON.parse(xml2json(xml, ""));
var nom = jsonObj.SubmitResponse.occurrences.occurrence.filter(x => x["#datasection"] === "TS")[0].data.filter(x => x.item === "NMPRES")[0].value;
var matcle = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0].data.filter(x => x.item === "MATCLE")[0].value;
var dossier = jsonObj.SubmitResponse.occurrences.occurrence.filter(function(x) {
return x["#datasection"] === "LM"
})[0]["#dossier"];
if ($('#population').val() != null && firstIter == false) {
}
return {
"nom": nom,
"matcle": matcle,
"dossier": dossier
};
}
function updateSelectMenu (ch) {
var txt = "";
var firstIter = true;
for (var key in ch) {
if (ch[key].matcle === matricule) {
txt += "<option value='" + ch[key].dossier + "'" + firstSelect(firstIter) + ">" + ch[key].nom + "</option>";
firstIter = false;
}
}
$('#population').html(txt)
}
RechercheFiltrée()
.then(getStockArray)
.then(getStocks)
.done(updateSelectMenu);
I have a for loop which loops about 16 times and each time it loops i want a value to be pushed to the array i declared outside the loop and the array is pushed from a nested ajax call in the loop. i wrote an if condition that if the loop reaches 16 times it should alert all the contents of the array at once but i'm getting an empty value
var comment = [];
for (var i = 0; i < jsons.length; i++){
var obj = jsons[i];
if( i == jsons.length - 1 )
{
alert(comment);
break;
}
var idno = '';
idno = obj.IDNO;
var amount = obj.AMOUNT;
(function(i)
{
$.ajax({
type: "POST",
url: "../include/salprefix.php",
data: {idnoauth: obj.IDNO, amount: amount, },
dataType: 'json',
cache: false,
success: function(result){
if(result[0].idno == '')
{
alert(result[0].idno + " " + result[0].amount);
}
else if(result[0].idno != ''){
var idnoresult = result[0].idno;
var amountresult = result[0].amount;
$.ajax({
type: "POST",
url: "../include/salprefix.php",
data: {idnoinsert: idnoresult, amountinsert: amountresult},
cache: false,
success: function(gg){
if(gg != '')
{
comment[i] = gg;
}
}
});
}
}
});
})(i);
}
the updated one is still not working as expected its returning an empty array
var comment = [];
for (var i = 0; i < jsons.length; i++){
//var comments = [];
var obj = jsons[i];
/*if (typeof obj.IDNO === 'string' && obj.IDNO.length)
{
alert('good');
}
else{
alert('bad');
}*/
//alert(obj.REASON);
//console.log(obj);
//alert(obj.REASON);
if( i == jsons.length - 1 )
{
alert(comment);
break;
}
var idno = '';
idno = obj.IDNO;
var amount = obj.AMOUNT;
var jqxhr1 = $.ajax({
type: "POST",
url: "../include/salprefix.php",
data: {idnoauth: obj.IDNO, amount: amount, },
dataType: 'json',
});
var jqxhr2 = $.ajax({
type: "POST",
url: "../include/salprefix.php",
data: {idnoinsert: obj.IDNO, amountinsert: amount},
});
$.when(jqxhr1, jqxhr2).then(function(result, gg) {
//alert(result[0].idno + " " + result[0].amount);
if(result[0].idno == ''/*&& result[0].amount == '' && result[0].idnoerror != ''*/)
{
alert(result[0].idno + " " + result[0].amount);
comments.push(result);
}
else if(result[0].idno != ''/* && result[0].amount != '' && result[0].idnoerror == ''*/){
var idnoresult = result[0].idno;
var amountresult = result[0].amount;
if(gg != '')
{
comment.push(gg);
/*if( i == jsons.length - 1 )
{*/
//alert(gg);
//alert(comments);
//break;
//}
}
}
//alert(idnoresult + " " + amountresult);
// Handle both XHR objects
//alert("all complete");
});
//})(i);
}enter code here
function GetViewModelData() {
var RDcViewModel = [];
var recordId = $.trim($("#recordId").val());
for (i = 1; i <= rowCount; i++) {
var item1 = $.trim($("#item1" + i).val()) == '' ? 0 : parseInt($("#item1" + i).val());
var item2 = $.trim($("#item2" + i).val()) == '' ? 0 : parseInt($("#item2" + i).val());
var GrandTotal = (item1 + item2);
var rdtCViewModel = new ItemDetailsViewModel(0, item1, item2, GrandTotal);
RDcViewModel.push(rdtCViewModel);
}
var obj = new ReportViewModel(recordId, RDcViewModel);
var viewmodel = JSON.stringify(obj);
return viewmodel;
}
I have the above sample function that i'm using to iterate over html table rows and storing the row values in an array.
Once i have my array populated, i'm using below code snippet to post the data to my controller.
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
//i want to check from here if viewmodel has any item(row) where GrandTotal is 0 (zero)
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function (data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function (e) {
return false;
}
});
});
}
What i now want to do in my PostData function is to check if my "viewmodel" object contains any item(row) where "GrandTotal" is 0.
using JSON.parse(viewmodel), prepare object of type ReportViewModel with RDcViewModel JS array of type ItemDetailsViewModel and iterate over it to find if any grandtotal == 0 for ItemDetailsViewModel instances
var viewmodel = GetViewModelData(),
var obj = JSON.parse(viewmodel);
var bFoundZero=false;
$.each(obj.RDcViewModelArray, function(idx, elem){
if( elem.GrandTotal === 0 ) bFoundZero=true;
})
if( bFoundZero ) return 0;
As you have stringified it, now you have to parse it back if you want to access its keys and values:
var PostData = function() {
$(".btnSubmit").click(function() {
var viewmodel = GetViewModelData(),
viewObj = JSON.parse(viewmodel),
flag = false; // <-----parse it back here
viewObj.forEach(function(i, el){
flag = el.GrandTotal === 0;
return flag;
});
if(flag){ return false; } // <------ and stop it here.
$.ajax({
async: true,
cache: false,
contentType: 'application/json; charset=utf-8',
data: viewmodel,
headers: GetRequestVerificationToken(),
type: 'POST',
url: '/' + virtualDirectory + '/Item/DataSave',
success: function(data) {
if (data == true) {
window.location.href = '/' + virtualDirectory + '/Destination/Index';
}
},
error: function(e) {
return false;
}
});
});
}
There is no point iterating array again. Break the loop in GetViewModelData() and return false from that function. Then test it in PostData
Inside existing for loop:
var GrandTotal = (item1 + item2);
if(!GrandTotal){
return false;
}
Then in PostData()
var PostData = function () {
$(".btnSubmit").click(function () {
var viewmodel = GetViewModelData();
if(viewmodel === false){
alert('Missing total');
return; //don't proceed
}
/* your ajax */
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.