JSON parsed object and wild card - javascript

I have a function that is supposed to check old data against data. I am parsing data and oldData to get a JSON object respectively as dbData and formData are simply strings containing ID's and values for the HTMML form. The purpuse of the function is to check if the user has made any textchanges some textareas in the HTML form. I want to do this by checking the ID for each textarea and then check if the value in formData and Data are the same. In that case no change has been made and the function will return true.
The data string im parsing looks something like this:
"[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\Apple \",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]"
So for example, i have to check the ID for "textarea1" in dbData and formData and then check if the value is the same. Can this be done using wildcard or is there a better way to archive this?
function CheckValues() {
var isChanged = false;
var formData = $.parseJSON(data);
var dbData = $.parseJSON(oldData);
if(formData !== dbData) {
var isChanged = true;
}
return isChanged;
}

The code shown below works in IE9+, Chrome, FireFox but other
browsers yet to test. The example shows two different values, data and
OldData - data contains "Tea" where as OldData contains "OldTea" so
isChanged flag is true.
function CheckValues() {
var data = "{\"disable\":false,\"textarea1
\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3
\":\"Milk\",\"textarea4\":\"Coffe\",\"textarea5\":\"Tea\"}";
var oldData = "{\"disable\":false,\"textarea1
\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3
\":\"Milk\",\"textarea4\":\"Coffe\",\"textarea5\":\"OldTea\"}";
var formData = JSON.parse(data);
var dbData = JSON.parse(oldData);
var oFormData = Object.keys(formData);
var oDbData = Object.keys(dbData);
var isChanged = false;
if (oFormData.length === oDbData.length)
{
for (var i = 0; i < oFormData.length; i++) {
var propName = oFormData[i];
if (typeof (dbData[propName]) === "undefined") {
isChanged = true;
break;
}
else {
if (formData[propName] !== dbData[propName]) {
isChanged = true;
break;
}
}
}
}
}

Related

Passing URL query strings into HTML form fields using Javascript

I have always used PHP for passing query strings into forms, but I am looking to move to a static site scenario and need the query data from a URL to populate the form fields.
I have the code with no console errors, but the data is not passing into the form fields. Does anyone know how this can be done that works across all modern and legacy browsers?
function getQueryString() {
var result = {};
if(!window.location.search.length) return result;
var qs = window.location.search.slice(1);
var parts = qs.split("&");
for(var i=0, len=parts.length; i<len; i++) {
var tokens = parts[i].split("=");
result[tokens[0]] = decodeURIComponent(tokens[1]);
}
return result;
}
$(document).ready(function() {
$("#theForm").submit(function(e) {
//var that = this;
var qs = getQueryString();
for(var key in qs) {
var field = $(document.createElement("input"));
field.attr("name", key).attr("type","hidden");
field.val(qs[key]);
$(this).append(field);
}
});
});
https://formpopulate.netlify.com/index.html?name=john&email=john#aol.com
https://formpopulate.netlify.com/
You should use URL seachParams:
var params = (new URL("https://example.com/?name=Jonathan&age=18&test=a%20long%20string")).searchParams;
var name = params.get("name"); console.log(name); // is the string "Jonathan"
var age = parseInt(params.get("age")); console.log(age);// is the number 18
var test = params.get("test"); console.log(test); // is a long string

JSON encode array parse correctly via Javascript

EXPLANATION
So from PHP to JavaScript encoded JSON array is sent in following:
$qa = array('question' => $question, 'a1' => $answer1, 'a2' => $answer2, 'a3' => $answer3);
echo json_encode($qa, JSON_UNESCAPED_UNICODE);
In JavaScript when I'm using like this (take a look at drawOutput):
function getSuccessOutput() {
getRequest(
't.php', // demo-only URL
drawOutput,
drawError
);
return false;
}
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req .readyState == 4){
return req.status === 200 ?
success(req.responseText) : error(req.status)
;
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
I got following output:
{"question":"This is my question?","a1":"answer1","a2":"answer2","a3":"answer3"}
DESIRED RESULTS
I need extract each value from this array and assign to variables, example:
var myQuestion = "This is my question?";
var answ1 = "answer1";
var answ2 = "answer2";
var answ3 = "answer3";
WHAT I'VE TRIED
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
// OUTPUT: {"question":"This is my question?","a1":"answer1","a2":"answer2","a3":"answer3"}
container.innerHTML = responseText[0];
// OUTPUT: <
container.innerHTML = responseText[a1];
// OUTPUT: nothing (blank)
}
Also I've tried:
function drawOutput(responseText) {
$.getJSON("t.php", function(responseText){
var container = document.getElementById('output');
var theObject = JSON.parse(responseText);
container.innerHTML = theObject[a1];
});
}
// OUTPUT: nothing (blank)
Also I've tried to use var theObject = JSON.parse(JSON.stringify(responseText)); instead of var theObject = JSON.parse(responseText); in this case output: undefined
If I'm using in following:
function drawOutput(responseText) {
var container = document.getElementById('output');
var theObject = JSON.parse(responseText);
container.innerHTML = theObject[a1];
}
// Output: nothing (blank)
But I got an error in browser's console: SCRIPT1014: Invalid character
I've read many similar issues, but nothing helped in my case. Have you any ideas, how could I solve It?
UPDATE
That's what I'm trying now and have nothing as output (blank):
function drawOutput(responseText) {
$.getJSON("t.php", function(responseText){
var question = theObject.question; // Get the question
var a1 = theObject.a1; // Get the answers
var a2 = theObject.a2;
var a3 = theObject.a3;
var container = document.getElementById('output');
container.innerHTML = a1;
alert(a1);
});
}
Parsing it is correct. If you get the text via XMLHttpRequest, you'll need to use JSON.parse on responseText. If you use jQuery's $.getJSON, it will do it for you and give you the parsed result.
The problem is how you're trying to access the values from the result. In theObject[a1], you're trying to use a variable called a1, whose value will then be used as the name of the property to get. Instead, use theObject.a1 or theObject["a1"].
So here, where you're using getJSON and so it's already been parsed for you:
function drawOutput() {
$.getJSON("t.php", function(theObject){ // Note: Not `responseText`, a parsed object
var question = theObject.question; // Get the question
var a1 = theObject.a1; // Get the answers
var a2 = theObject.a2;
var a3 = theObject.a3;
// ...use them...
});
}
Side note: Instead of separate a1,a2, anda3` properties on the object you're returning, you might consider using an array.
$qa = array(
'question' => $question,
'answers' => array($answer1, $answer2, $answer3)
);
echo json_encode($qa);
then
function drawOutput() {
$.getJSON("t.php", function(theObject){
var question = theObject.question; // Get the question
var answers = theObject.answers; // Get the answers
// ...use question, and `answers[0]` through `answers[2]`, where
// you can get the number of answers from `answers.length`...
});
}
You can access object values with one of these method:
var responseText = '{"question":"This is my question?","a1":"answer1","a2":"answer2","a3":"answer3"} ';
var theObject = JSON.parse(responseText);
console.log(theObject['a1']); // a1 in string
console.log(theObject.a1); // Gives the same result
In PHP you need to json_encode your response :
$ServerResponse= json_encode($MyJSON);
In Javascript you need to JSON.parse the response you got from PHP :
var myJSONObject = JSON.parse(ServerResponse);
After that , you have a normal Object in your hands , and that is myJsonObject. You can access its properties either with the use of "dot" (Eg. myJsonObject.PROPERTY_NAME) or with brackets (Eg myJsonObject["PROPERTY_NAME"]).

How to get values from json array in a javascript

I'm trying to get values from json array inside a javascript. Below is the part of my javascript file. I'm using jsondata.value to get the values. It's displaying the json data correctly on the console, but jsondata.value is not working for getting the values.
I'm guessing that your "jsondata" is text in the DOM? If so, you want to grab the "string" in the DOM and Parse it into a valid JavaScript Object. To do so, you need to grab it appropriately:
var jsondata = document.getElementById("jsonArray").value;
Then you need to parse it
var jsondataObj = JSON.parse(jsondata);
At this point, jsondataObj is your data. If you want to populate this into your grid, simply inject it the way you wanted to. There is no need for XHRHttpRequest since you already injected your data into the DOM:
var gridOptions = { ... [your options here] };
document.addEventListener('DOMContentLoaded', function() {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
var jsondata = document.getElementById("jsonArray").value;
var jsondataObj = JSON.parse(jsondata);
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var parsedData = jsondataObj.map(function(obj) {
return Object.keys(obj).reduce(function(memo, key) {
var value = obj[key];
memo[key] = isNumeric(value) ? Number(value) : value;
return memo;
}, {})
})
console.log(parsedData);
gridOptions.api.setRowData(parsedData);
});

Array value becomes null while passing from Ajax

I am making an ajax call in my javascript submit function. In this ajax call, I am passing an array(globalSelection) as data to the servlet. This array consists elements of function textSelection which is also pasted below.
globalSelection =[];
function submit() {
console.log("globalSelection start")
console.log(globalSelection)
console.log("globalSelection end")
$.ajax({
async : false,
type : "POST",
url : 'http://example.com:8080/myApp/DataServlet',
data: {globalSelection:globalSelection},
success : function(data) {
alert(data)
},
error : function(data, status, er) {
alert("error: " + data + " status: " + status + " er:" + er);
}
});
}
function textSelection(range, anchorNode, focusNode) {
this.range = range;
this.type = 3;
this.rCollection = [];
this.textContent = encodeURI(range.toString());
this.anchorNode = anchorNode;
this.focusNode = focusNode;
this.selectionId = getRandom();
this.yPOS = getYPOS();
this.getTagName = function(range) {
var el = range.startContainer.parentNode;
return el;
}
this.getTagIndex = function(el) {
var index = $(el.tagName).index(el);
return index;
}
this.simpleText = function(node, range) {
if (!node)
var entry = this.createEntry(this.anchorNode, this.range);
else
var entry = this.createEntry(node, range);
this.rCollection.push(entry);
this.highlight(this.rCollection[0].range);
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
this.compositeText = function() {
this.findSelectionDirection();
var flag = this.splitRanges(this.anchorNode, this.focusNode,
this.range.startOffset, this.range.endOffset);
if (flag == 0) {
for (j in this.rCollection) {
this.highlight(this.rCollection[j].range);
}
}
this.crossIndexCalc();
textSelection._t_list.push(this);
pushto_G_FactualEntry(this);
}
}
I am ading the screen of my browser console below, which prints the globalSelection(array).
In my servlet I am getting this array as follows
String[] arrays = request.getParameterValues("globalSelection[]");
System.out.println(arrays);
Here I am getting null value for arrays.
If I put globalSelection as follows in submit function for simple test to servlet, I am able to get the arrays.
var globalSelection = ["lynk_url", "jsonBody", "lynk_dummy1", "lynk_dummy2", "lynk_name", "lynk_desc", "lynk_flag"];
Why my actual globalSelection is shows null in servlet, what I am doing wrong here.
Try with :
String[] arrays = request.getParameterValues("globalSelection");
System.out.println(arrays);
Because the parameter submitted with name "globalSelection" only not "[]" symbol.
I see your problem and I have a simple solution.
I recommend in that case that you convert the array as a string in JS:
JSON.stringify(globalSelection)
and then reconstructing the object on the backend using some sort of library for JSON conversion like: https://code.google.com/archive/p/json-simple/
You could then do something like this:
JSONArray globalSelection = (JSONArray) new JSONParser().parse(request.getParameter("globalSelection"));
Iterator i = globalSelection.iterator();
while (i.hasNext()) {
JSONObject selection = (JSONObject) i.next();
String type = (String)selection.get("type");
System.out.println(type);
}
This will parse your array and print the selection type. Try it, hope it helps.

jQuery .ajax() POST Only checkboxes :checked

I am getting an error in my .ajax() function when attempting to pass in the checkboxes
Here is the code:
if(typeof($post) !== 'undefined'){
var $fname = $($post).attr('name').toString();
var data = {$fname : []};
alert($post);
alert($fname);
$($post + ":checked").each(function() {
data[$fname].push($(this).val());
});
}else{
var data = null;
}
The error I am getting in firebug is: data[$fname].push($(this).val()); is undefined
$post is just a class name passed into the function.. in this case it's .del-checked
The alerts sucessfully alert me the class name, and the checkbox name... in this case it's del[]
How can I get this to work in order to pass it to the data option of $.ajax?
Because you can not use a variable as a key when creating a new object
var data = {$fname : []};
is the same thing as doing
var data = {"$fname" : []};
You need to create the object and add the key with brackets
var data = {};
data[$fname] = [];
You can't use variables as keys unless you use bracket notation
if (typeof($post) !== 'undefined'){
var $fname = $($post).attr('name');
var data = {};
data[$fname] = [];
$($post).filter(":checked").each(function() {
data[$fname].push( this.value );
});
}else{
var data = null;
}
What about:
var data = $($fname).serialize();

Categories