Resubmitting or Creating a Nested jQuery.post - javascript

I have a variable in Javascript which I am trying to pass to PHP. I have this working using jQuery.post. The issue is, the variable (linkforsharedURL) is declared within a multidimensional array and the default value is immediately sent when the jQuery.post command is executed. However the value of this variable is further modified within the function, but the modified value is not sent to PHP - the original value is sent.
A solution forward I was considering was to execute another jQuery.post just after the If statement again containing the updated 'data' array - but I don't think this would be best practice.
I did consider bringing the If statement out of the jQuery.post, however the If statement is dependent on the jQuery's response variable.
My apologies for the way I have explained the above - just trying to get my head round this particular issue.
// build data
var dataURL = dataURLs[0],
data = {
email: email,
name: name
linkforsharedURL: linkforsharedURL
};
// send data
jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function(response) {
if (response.share_id !== undefined) {
var pattern = new RegExp('(share_id=).*?(&|$)'), shareUrl = window.location.href;
if (shareUrl.search(pattern) >= 0) {
shareUrl = shareUrl.replace(pattern, '$1' + response.share_id + '$2');
linkforsharedURL = shareUrl;
}

You have to create a function to call again within jQuery.post response. try the below code.
// build data
var dataURL = dataURLs[0],
data = {
email: email,
name: name,
linkforsharedURL: linkforsharedURL
};
SendDataToPhp( data );
function SendDataToPhp(){
// send data
jQuery.post("<?php echo admin_url('admin-ajax.php'); ?>", data, function(response) {
if (response.share_id !== undefined) {
var pattern = new RegExp('(share_id=).*?(&|$)'), shareUrl = window.location.href;
if (shareUrl.search(pattern) >= 0) {
shareUrl = shareUrl.replace(pattern, '$1' + response.share_id + '$2');
linkforsharedURL = shareUrl;
data.linkforsharedURL = 'updated value to send';
SendDataToPhp( data );
}
}
});
}

Related

Passing javascript object containing another array of objects to localStorage and then to java servlet using ajax

I am trying to work out how to store a javascript object in local storage that has a few items as well as an array of objects, if that is possible. To then extract the data from the local storage and send to a java servlet using ajax, then extract the data from the java HttpServletRequest. Here is some of the code I have written. It's a bit too complex to put the entire code base here. I have multiple forms which a user completes and as they move between forms I store the data entered into local storage.
const object = localStorage.getItem(scenarioName);
let scenarioObject = JSON.parse(object);
if (formIsValid) {
scenarioObject.SUPER_BALANCE = 420000;
scenarioObject.SUPER_INVESTMENT_FEES = 0.14;
scenarioObject.SUPER_ADMIN_FEES = 120;
scenarioObject.LIFE_INSURANCE = 200000;
scenarioObject.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION = 1500;
let objectString = JSON.stringify(scenarioObject);
localStorage.setItem(scenarioName, objectString);
}
To extract the data from local storage I do the following:
const object = localStorage.getItem(activeScenario);
const jsonString = JSON.parse(object);
const yourSuperBalance = jsonString.SUPER_BALANCE;
$("#your-super-balance").val(yourSuperBalance);
const yourInvestmentFees = jsonString.SUPER_INVESTMENT_FEES;
$("#super-investment-fees").val(yourInvestmentFees);
const yourSuperAdminFees = jsonString.SUPER_ADMIN_FEES;
$("#super-admin-fees").val(yourSuperAdminFees);
const yourInsurance = jsonString.LIFE_INSURANCE;
$("#life-insurance").val(yourInsurance);
const yourAnnualSuperContribution = jsonString.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION;
$("#your-annual-lump-sum-super-contribution").val(yourAnnualSuperContribution);
This all works fine, but now I wanted to add an array of objects from a table. I could not figure out a way to add this so I ended up storing two items in local storage. One for all the form data and one for the table data. I didn't like this approach but couldn't get it to work otherwise. Here is how I did the table:
function getSuperContributionsTableDataString(table) {
let yourSuperContributionsTableData = [];
let jsonData;
// commence for loop at 1 because the first row will be the header row and we want to skip that
for (let i = 1; i < table.rows.length; i++) {
let row = table.rows[i];
// first check all cells in row have a value, if not ignore
if (row.cells[0].innerText !== "" && row.cells[1].innerText !== "" && row.cells[2].innerText !== "") {
// As we are pushing the last element pushed becomes the first element in the array
// therefore, we push the before or after tax first and age last
jsonData = {};
jsonData[SUPER_TAXATION_CONTRIBUTION] = row.cells[2].innerText;
jsonData[SUPER_AMOUNT_CONTRIBUTION] = row.cells[1].innerText;
jsonData[SUPER_AGE_CONTRIBUTION] = row.cells[0].innerText;
yourSuperContributionsTableData.push(jsonData);
}
}
return JSON.stringify(yourSuperContributionsTableData);
}
let superContributionsTableDataString = getSuperContributionsTableDataString(
document.getElementById("your-extra-super-contributions-table"));
localStorage.setItem(scenarioName+ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION, superContributionsTableDataString);
This all worked but then I had to figure out how to send this data to the server using ajax. Without the table, everything was working fine as follows:
function sendScenarioDetailsToServer() {
let activeScenario = localStorage.getItem(ACTIVE_SCENARIO_KEY);
let item = localStorage.getItem(activeScenario);
let passedData = JSON.parse(item);
$.ajax({
type: "POST",
url: "ScenarioServlet",
data: passedData,
success: function (data) {
const SUCCESS_INT = data.length - 1;
if (data[SUCCESS_INT].SUCCESS === FAIL) {
displayPopupMessage("Error saving scenario ", "Save Scenario");
}else {
displayResult();
}
},
error: function (error, status) {
console.log(`Error ${error}`);
const stackTrace = getStackTrace();
const message = "An error occurred sending your data to the server for calculation. ";
displayPopupMessage(message, "Server Error.", stackTrace);
}
});
}
I modified this function as follows to add the table data and everything in the java servlet code went wrong.
function sendScenarioDetailsToServer() {
let activeScenario = localStorage.getItem(ACTIVE_SCENARIO_KEY);
let item = localStorage.getItem(activeScenario);
let passedData = JSON.parse(item);
// superannuation table
const superTable = activeScenario+ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION;
// this is already stringified
const superTableItem = localStorage.getItem(superTable);
const superTableData = '&' + ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION + "=" + superTableItem;
const formData = passedData + superTableData;
console.log("formData " + formData);
$.ajax({
type: "POST",
url: "ScenarioServlet",
data: passedData + superTableData,
success: function (data) {
const SUCCESS_INT = data.length - 1;
if (data[SUCCESS_INT].SUCCESS === FAIL) {
// TODO display messages
displayPopupMessage("Error saving scenario ", "Save Scenario");
}else {
displayResult();
}
},
error: function (error, status) {
console.log(`Error ${error}`);
const stackTrace = getStackTrace();
const message = "An error occurred sending your data to the server for calculation. ";
displayPopupMessage(message, "Server Error.", stackTrace);
}
});
}
Can anyone advise how best to store a javascript object in local storage that has an item inside the object which is an array of objects for a table? How do I store this in local storage, retrieve it from local storage, send it to the java servlet using ajax and then retrieve it from the HttpServletRequest. Any assistance would be much appreciated.
I worked out a way to do this. I shall fully explain the situation and then my solution to the problem. Not sure if this is the best solution but it does work.
The situation is that I have multiple forms where the user enters data for calculations, including a table of data. I wanted to store this data on local storage for later retrieval next time the user uses the website. The calculations are done in Java on the server so when the user clicks on something like "calculate" the data in local storage is then sent to the server to perform the calculations and the result is sent back.
I needed to store a javascript object containing some elements plus a table, so basically a javascript object with an array inside it.
Collect data from the table
function getSuperContributionsTableDataString(table) {
let yourSuperContributionsTableData = [];
let jsonData;
// commence for loop at 1 because the first row will be the header row and we want to skip that
for (let i = 1; i < table.rows.length; i++) {
let row = table.rows[i];
// first check all cells in row have a value, if not ignore
if (row.cells[0].innerText !== "" && row.cells[1].innerText !== "" && row.cells[2].innerText !== "") {
// As we are pushing the last element pushed becomes the first element in the array
// therefore, we push the before or after tax first and age last
jsonData = {};
jsonData[SUPER_TAXATION_CONTRIBUTION] = row.cells[2].innerText;
jsonData[SUPER_AMOUNT_CONTRIBUTION] = row.cells[1].innerText;
jsonData[SUPER_AGE_CONTRIBUTION] = row.cells[0].innerText;
yourSuperContributionsTableData.push(jsonData);
}
}
return yourSuperContributionsTableData;
}
Where I went wrong with this originally was I stringified the array. As the entire javascript object is going to be stringified this was unnecessary.
Create javascript object and store in local storage
The first step is to extract the item from local storage to update it with the new data from the user. Notice we must parse the object because it was originally stringified.
Secondly set the user entered data on the javascript object. You will notice the call to the function above that retrieves the table data. That table data is set as a key value pair in the javascript object.
const scenarioName = localStorage.getItem(ACTIVE_SCENARIO_KEY);
const object = localStorage.getItem(scenarioName);
let scenarioObject = JSON.parse(object);
isValid = validateYourSuperannuationForm();
if (isValid) {
let superContributionsTableDataString = getSuperContributionsTableDataString(
document.getElementById("your-extra-super-contributions-table"));
scenarioObject.SUPER_BALANCE = $("#your-super-balance").val();
scenarioObject.SUPER_INVESTMENT_FEES = $("#super-investment-fees").val();
scenarioObject.SUPER_ADMIN_FEES = $("#super-admin-fees").val();
scenarioObject.LIFE_INSURANCE = $("#life-insurance").val();
scenarioObject.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION = $("#your-annual-lump-sum-super-contribution").val();
scenarioObject.EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA = superContributionsTableDataString;
let objectString = JSON.stringify(scenarioObject);
localStorage.setItem(scenarioName, objectString);
}
Send item in local storage to server
I discovered trying to stringify the entire javascript object caused problems at the server. What I had to do was create a new object for the formData to be sent to the server, BUT I had to stringify only the table data, not the entire object. I had to retrieve each item from local storage and set it on the formData object to be passed to the server.
function sendScenarioDetailsToServer() {
const activeScenario = localStorage.getItem(ACTIVE_SCENARIO_KEY);
const item = localStorage.getItem(activeScenario);
const scenarioObject = JSON.parse(item);
// We must do this because if superContributionsTableData == "" and we then stringify this it will
// end up with a value of """", which will cause an error.
const superContributionsTableData = scenarioObject.EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA;
let superContributionsTableDataString = "";
if (superContributionsTableData !== ""){
superContributionsTableDataString = JSON.stringify(superContributionsTableData);
}
const formData = {
SCENARIO_NAME: scenarioObject.SCENARIO_NAME,
DATE_OF_BIRTH: "",
IS_SINGLE: scenarioObject.IS_SINGLE,
IS_RETIRED: scenarioObject.IS_RETIRED,
RETIREMENT_DATE: scenarioObject.RETIREMENT_DATE,
IS_HOMEOWNER: scenarioObject.IS_HOMEOWNER,
FORTNIGHTLY_RENT: scenarioObject.FORTNIGHTLY_RENT,
DATE_RENT_CEASES: scenarioObject.DATE_RENT_CEASES,
IS_SINGLE_AND_SHARING: scenarioObject.IS_SINGLE_AND_SHARING,
SPOUSE_DATE_OF_BIRTH: scenarioObject.SPOUSE_DATE_OF_BIRTH,
IS_SPOUSE_RETIRED: scenarioObject.IS_SPOUSE_RETIRED,
SPOUSE_RETIREMENT_DATE: scenarioObject.SPOUSE_RETIREMENT_DATE,
SUPER_BALANCE: scenarioObject.SUPER_BALANCE,
SUPER_INVESTMENT_FEES: scenarioObject.SUPER_INVESTMENT_FEES,
SUPER_ADMIN_FEES: scenarioObject.SUPER_ADMIN_FEES,
LIFE_INSURANCE: scenarioObject.LIFE_INSURANCE,
ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION: scenarioObject.ANNUAL_LUMP_SUM_SUPER_CONTRIBUTION,
EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA: superContributionsTableDataString
}
$.ajax({
type: "POST",
url: "ScenarioServlet",
data: formData,
success: function (data) {
// do stuff here
{
},
error: function (error, status) {
console.log(`Error ${error}`);
const stackTrace = getStackTrace();
const message = "An error occurred sending your data to the server for calculation. ";
displayPopupMessage(message, "Server Error.", stackTrace);
}
});
In the Java Servlet the data is then extracted from the HttpServletRequest passed to the doPost method. It is retrieved in the usual way by calling HttpServletRequest.getParameter. Converting the table data is a little more complex because it is an array that was converted to a string. I am including an extract of that code in case it is of use to someone.
ArrayList<LumpSumSuperContribution> superContributionsList = new ArrayList<>();
String superContributionsTableData = request.getParameter(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA);
// Array superContributionsArray = request.getParameter(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA);
JSONObject superContributionsMessage = new JSONObject();
boolean errorOccurred = false;
if (superContributionsTableData != null && superContributionsTableData.length() > 0) {
try {
JSONArray superContributionsArray = new JSONArray(superContributionsTableData);
int i = 0;
while (i < superContributionsArray.length()) {
JSONObject contributionObj = (JSONObject) superContributionsArray.get(i);
String ageString = (String) contributionObj.get(SUPER_AGE_CONTRIBUTION);
Validator.WholeNumberResult result6 = Validator.validateMandatoryWholeNumber(ageString, 18, 99,
"Lump Sum Super Contribution age for row " + (i + 1));
if (!result6.getErrorMessage().equals(SUCCESS)) {
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, result6.getErrorMessage());
messageArray.put(superContributionsMessage);
errorOccurred = true;
break;
}
Integer age = result6.getNumber();
String contributionAmountString = (String) contributionObj.get(SUPER_AMOUNT_CONTRIBUTION);
Validator.WholeNumberResult result7 = Validator.validateMandatoryWholeNumber(
contributionAmountString, 1, 9999999,
"Lump Sum Super Contribution amount for row " + (i + 1));
if (!result7.getErrorMessage().equals(SUCCESS)) {
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, result7.getErrorMessage());
messageArray.put(superContributionsMessage);
errorOccurred = true;
break;
}
Integer amount = result7.getNumber();
String beforeAfterTaxString = (String) contributionObj.get(SUPER_TAXATION_CONTRIBUTION);
Validator.TextResult result8 = Validator.validateMandatoryText(beforeAfterTaxString,
"Lump Sum Super Contribution Before or After Tax for row " + (i + 1), 5, 6);
if (!result8.getErrorMessage().equals(SUCCESS)) {
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, result8.getErrorMessage());
messageArray.put(superContributionsMessage);
errorOccurred = true;
break;
}
String beforeAfterTax = result8.getText();
LumpSumSuperContribution superContribution = new LumpSumSuperContribution(age, amount, false,
LumpSumSuperContribution.YOUR_CONTRIBUTION, beforeAfterTax);
superContributionsList.add(superContribution);
i++;
}
if (!errorOccurred) {
scenario.setAllYourSuperContributions(superContributionsList);
// superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, SUCCESS);
} else {
fail = true;
superContributionsMessage.put(EXTRA_SUPER_CONTRIBUTIONS_TABLE_DATA, FAIL);
messageArray.put(superContributionsMessage);
}
} catch (JSONException e) {
throw new RuntimeException(e);
}
}else {
scenario.setAllYourSuperContributions(null);
}
}
Summary
Create a javascript array. Then loop through the table data and create a javascript object for each row of the table and push onto the array.
Create or retrieve javascript object stored in local storage. If already in local storage, this object must be parsed using JSON.parse(object).
Set the details on the object entered by the user.
Stringify the javascript array and add the string to the object as a key value pair.
To send the data to the server retrieve the item from local storage and parse the item to extract details from it.
Set the extracted details on a newly created formData object.
Stringify the table data and set as a key value pair in formData.
Using ajax Post the data to the server.
I hope this helps someone in the future. It took me a while of trying different things to find a way to get this to work. If anyone has a better solution please post it.

Best practice for sending JSON to php with keeping field types

Obviously, if I send JSON data to php using an AJAX post or get request I will end up only receiving string data type in the php $_POST variable.
What is best practice for sending JSON fields but keeping their data types? My idea would be to send the whole JSON in one $_POST field, and then decoding it one more time.
So in JavaScript instead of:
$.post('test.php', {"stringparm":"a string","numparm": 66,"boolparm":true)}, function (result) ...
I would use:
params = '{"stringparm":"a string","numparm": 66,"boolparm":true)}';
$.post('test.php', {'params': params}, function (result) {
....
}
And in php I would:
$params = json.decode($_POST['params']);
or is there a better way?
My recommendation would be to send them as a query string using Fetch or Axios, you can use Ajax as well and it should send the various datatypes properly, and then parse the query string in PHP like this.
parse_str($_SERVER['QUERY_STRING'], $data);
$data = (object) $data;
I'm sure you know what your standard query string looks like
https://example.com/?user_id=value&someotherdata=value etc...
Once you have the $data object you can access the values with the arrow -> operator.
$user_id = $data->user_id
Here is a script I use to create a query string from a provided object.
prepareQuerystring(url, paramsObject, isParamsObjectUsed, phpMethod = '') {
if (url !== '') {
let postUrl = `${url}${phpMethod}`;
if (isParamsObjectUsed) {
postUrl += `?`;
let it = 0;
let len = Object.keys(paramsObject).length
for (let i in paramsObject) {
if (it === len - 1) {
postUrl = postUrl + [i] + '=' + paramsObject[i];
} else {
postUrl = postUrl + [i] + '=' + paramsObject[i] + '&';
}
it++;
}
return postUrl;
} else {
postUrl = `${url}${phpMethod}/`;
return postUrl;
}
} else {
let postUrl = `${window.location.href}${phpMethod}/`;
if (isParamsObjectUsed) {
postUrl += `?`;
let it = 0;
let len = Object.keys(paramsObject).length
for (let i in paramsObject) {
if (it === len - 1) {
postUrl = postUrl + [i] + '=' + paramsObject[i];
} else {
postUrl = postUrl + [i] + '=' + paramsObject[i] + '&';
}
it++;
}
return postUrl;
} else {
postUrl = `${window.location.href}${phpMethod}/`;
return postUrl;
}
}
}
The url argument is your base url (https://example.com)
The paramObject is your JSON object which is just an object in Javascript.
{
user_id: 1,
someotherdata: 'shoe'
}
The PHP method argument is there to call a specific method in php, it simply gets appended after the base url, my API lets me make calls this way, yours might not so you can just leave that as an empty string ''.
And the isParamsObjectUsed is a boolean, if you pass an object in the second argument then this will be true, I honestly can't recall ever setting it to false so may need to refactor and remove that eventually.
Heres an example of how to use it.
let url = prepareQuerystring(
https://example.com/,
{
user_id: 1,
someotherdata: 'shoe',
someBool: true
},
true
)
You will have reference to all the parameters as their data type in PHP using this method. I use Axios to send http requests but this also works with Ajax and Fetch, I'd recommend using Fetch or Axios. Mostly because I can't remember how I got it working with Ajax, I typically use Fetch or Axios.
Using Fetch
fetch(url, { method: "POST" })
Hope this helps point you in the right direction. Let me know if you have any questions.

JSON array to and from MySql. Saving and Looping

<?
$cl = $row["saved_json_string_column"];
?>
expecting this output from the db query to create a new array
//cl = '[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]';
cl = '<? echo $cl;?>';
// I would like to start with the saved 'cl' array and push new items to it.
skptoQarry = new Array();
//javascript function loop (not shown) generates vars and pushes to new array.
thisItem_eid = 1;
yes_no_is_this = 'No';
SkipToTartgetEID = 5;
var skptoQarry_temp = {
"ifeid" : thisItem_eid,
"ans" : yes_no_is_this,
"type" : "SkipTo",
"target" : SkipToTartgetEID
};
skptoQarry.push(skptoQarry_temp);
cl = JSON.stringify(skptoQarry); //for ajax post to php for saving
//this is what is in saved the DB via ajax post
[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]
//...but when PHP echos it out only this comes out: cl = "[,]"
// I think i'm saving it wrong or echoing the column data the wrong way.
//read text from mysql and append where needed.
cl = $.parseJSON(cl);
jQuery.each(cl, function (i) {
jQuery.each(this, function (key, value) {
if (key == "ifeid") {
$('div').append('if this id: '+value+'<br>');
} else if (key == "ans") {
$('div').append('is: '+value+'<br>');
} else if (key == "type") {
$('div').append('then: '+value+'<br>');
} else if (key == "target") {
$('div').append('this id: '+value+'<br><br>');
}
});
});
function saveit(){
saved_logic_dialog = JSON.stringify(skptoQarry);
var posturl = "myurl?event=save&saved_logic_dialog="+saved_logic_dialog;
jQuery.ajax({
traditional: true,
type: "POST",
url: posturl,
success: function(data) {
//messages and stuff
}
});
}
//php
$loadvfsql = "SELECT `saved_logic_dialog` FROM `questions` WHERE `id` = '{$id}' ORDER BY `questions`.`question_order` ASC";
$loadv_result=mysql_query($loadvfsql);
while($rows=mysql_fetch_array($loadv_result)){
$clc = $rows['current_logic_cont'];
$cl = $rows['saved_logic_dialog'];
//more stuff
}
This will ensure your array of objects is properly encoded - jQuery will not encode the URL for you.
var posturl = "myurl?event=save&saved_logic_dialog=" + encodeURIComponent(saved_logic_dialog);
When saving to DB - check for properly escaping the value (as it will certainly contain quotes);
When echoing the value back into HTML - use htmlspecialchars($cl) to properly escape the symbols which might have special meaning in HTML.
Before using the value in JavaScript - use JSON.parse(cl) to convert from String into Array.

How do I display JSON data to an HTML DOM Element after JSON.parse()?

I have two functions I am using to pull JSON from my server side to then display it to HTML.
The first function that pulls the data from the route handler is successfully pulling the data and parsing it successfully with JSON.parse() and displaying the needed information to the console without issue. I am not having and ajax or route handling issue...
Here is how I am dealing with the JSON first in my function called "projectInfo()":
projInfo = JSON.stringify(data);
console.log("DEBUG DONE WITH CAPTURING project_info DATA: " );
// This console.log() prints the JSON string
// successfully pulled from route handler
// var projInfo is a local string var declared in the scope of
// this first function
console.log("var projInfo: " + projInfo);
// parse JSON data in projInfo and store in string var p
// string var p is a local var declared inside of the scope
// of this function
p = JSON.parse(projInfo);
console.log("Parsed Project JSON: " + p.Project);
// update "Global" pInfo with the value of the JSON data for
// "Project" as needed
pInfo = p;
console.log("What is inside of pInfo???: " + pInfo);
// This last console.log prints [object Object] to console
// How do I pul the value out of this Object?
The second function calls the first function in order to update a global variable with the parsed JSON data that I need to then display the global variable's data to the DOM element that I am trying to display.
Here is how I am trying to update my global var with a JSON Object in my function called "loginFun()":
// Call projectInfo() in order to update Global pInfo
// with the needed project info
projectInfo();
// This console.log() prints nothing...?
console.log("projectInfo var data should be aa2: " + pInfo);
document.getElementById("userBar").style.display = "";
// This is where I try to Display pInfo in the DOM but I only get Undefined...?
document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
When I JSON.parse() the data in the first function I run a console.log() statement and I get the needed data to print from a variable local to the function I am getting my JSON with using ajax and I verify that the function is in fact doing what I need so that part is good up until I get the [object Object] output.
I am having issues when I call this function from my second function to then try to use the global variable which should have the data stored.
when I try to use the global variable with the needed data I get an 'undefined'...
I have also tried returning the data that has been parsed in the first function to then storehttps://codepen.io/lopezdp/pen/owKGdJ the value returned into a local variable in the second function but I still get 'undefined'.
If you would like to see the complete code for both functions I have put them on a CodePen to make it easier at:
https://codepen.io/lopezdp/pen/owKGdJ
How can I get my Project Data to display in my DOM element?
EDIT: The JSON Data that I am using looks like this:
{"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}
I rewrote your login function like this and it worked for me. I also eliminated the projectInfo() function!
var allMn = [];
var tags = [];
var pInfo = '';
function loginFun() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert("Required fields cannot be left blank.");
} else {
$.ajaxSetup({
cache: false
});
$.ajax({
type: 'GET',
url: 'http://139.169.63.170:' + port + '/login/' + username + "zlz" + password,
cache: false,
success: function (data) {
// NEED SUB ROUTINE HERE FOR AJAX CALL DPL
// Make async call to ccdd tool database to get new data
// This collects allMn[] data!!!
getMnJson();
// END SUB ROUTINE HERE
// Checks to make sure user is logged in if not
// the condition redirects user to loginFun()
if (data.search("HTTP ERROR: ") != -1) {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
document.getElementById('searchResults').innerHTML = "Login Failed";
document.getElementById('searchRBar').style.display = "";
loginFun();
} else {
login = 1;
// Call projectInfo() in order to update pInfo with the needed project info
//projectInfo();
var projInfo = '';
var p = '';
// Get all Mn Data on startup tp display in DOM -DPL
$.ajax({
type: 'GET',
url: 'http://139.169.63.170:' + port + '/role',
dataType: 'json',
cache: true,
success: function (data) {
// projInfo = JSON.stringify(data);
console.log("DEBUG DONE WITH CAPTURING project_info DATA: " );
// console.log("var projInfo: " + projInfo);
// parse JSON data in projInfo
p = data['Project']; //JSON.parse(projInfo);
console.log("Parsed Project JSON: " + p);
// update "Global" pInfo with the value of the JSON data for "Project" as needed
pInfo = p;
console.log("What is inside of pInfo???: " + pInfo);
document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
}
}).fail(function () {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
console.log("Error. /role data access Error.");
});
console.log("projectInfo var data should be aa2: " + pInfo);
document.getElementById("userBar").style.display = "";
// Display pInfo in the DOM
// document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
$("div.create").children().remove();
//-------------------------------------------------------------------END OF GLOBAL VARIABLES
$.ajaxSetup({
cache: false
});
// get table data from proxy server on port 7071 DPL
// NEED SUB ROUTINE HERE FOR AJAX CALL
// Make call to server-side code to reload JSON data into table from port 7071
pushJsonData();
// END SUB ROUTINE HERE!!!
// getTblJson();
}
}
}).fail(function () {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
console.log("Error. Need user Credentials");
});
}
}

Parse an Array of Javascript Objects using JSON and AJAX

I have an array of Javascript objects, which I convert to a string using JSON.stringify() before processing with AJAX.
On the server side, all I am trying to do is verify that the proper $_POST["flavors"] variable is set, and output it's contents. I have verified (via a simple conditional) that the $_POST["flavors"] is being set, but I don't know how to modify the ajax call (or the PHP) to properly output it's contents.
I have read on here that I (may) need to set the dataType for the $.AJAX call and/or set the header in my PHP script, but I wasn't sure if setting the header would be applicable since it is inside my functions.php file. *
(Array function)
flavors = [];
function wholesaleAJAX() {
var sizeSelect = $('form#wholesale-size-form input:checked');
if (sizeSelect.val() === 'regularBag') {
$('select[name="wholesale-flavors-regular"] option:selected').each(function() {
name = $(this).text();
qty = $(this).closest('.row').find('div.large-3 select[name="wholesale-flavors-regular-count"] option:selected').text();
flavors.push(new FlavorSelects(name, qty));
});
} else if (sizeSelect.val() === 'largeBag') {
$('select[name="wholesale-flavors-large"] option:selected').each(function() {
name = $(this).text();
qty = $(this).closest('.row').find('div.large-3 select[name="wholesale-flavors-large-count"] option:selected').text();
flavors.push(new FlavorSelects(name, qty));
});
}
(Stringify the array and process AJAX)
stringArray = JSON.stringify(flavors);
$.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: "returnHash",
flavors: stringArray
},
success:function(data){
$("#ajax").html(data);
}
});
(PHP for processing AJAX in functions.php)
function returnHash() {
if (isset($_POST["flavors"])) {
$flavors = json_decode($_POST["flavors"]);
print_r($flavors);
} else {
echo 'Not Set';
}
die();
}
add_action('wp_ajax_returnHash', 'returnHash');
add_action('wp_ajax_nopriv_returnHash', 'returnHash');

Categories

Resources