I end up with an array filled with values like this:
var results = ['This is result 1',
'This is result 2. It could have a comma, semicolon or anything;',
'This is result 3'
];
All of the results will be stored in a single hidden field and then parsed on the server, but I feel like this could be problematic:
$('#hidden_results').val(results.join(','));
What would be a more elegant approach to doing something like this? I need to avoid potential parsing issues when this field is processed on the server.
Thanks!
Serialize the array using JSON.
$('#hidden_results').val(JSON.stringify(results));
To deserialize the value on the client side you can do this:
var results = JSON.parse($('#hidden_results').val());
To deserialize the value in PHP, use json_decode.
You could also do this :
results = '"' + results.map(function (v) {
return v.replace(/,/g, ',,');
}).join('","') + '"';
Then you can deserialize like this :
results = results.slice(1, -1).split('","').map(function (v) {
return v.replace(/,,/g, ',');
});
You can easily find PHP equivalents to Javascript functions.
Related
I have an array that comes in from from my API that I would like to arrange in a way that is better for the user (namely, in a column as opposed to the typical comma separated printed array).
This is my JS Fiddle to give a clearer picture: https://jsfiddle.net/2z89owas/
My question is, how can I get output3 to display just like output (and maintain its status as an iterable array like it was as dates)?
First you should not be using value for an html element. You can use .value for extracting value from inputs. Change your line to:
var val = document.getElementById('output2').innerHTML;
Afterwards, you have to split the same way you did join.
var dates3 = val.split('<br>');
document.getElementById('output3').innerHTML = dates3;
You can directly use join, something like:
document.getElementById('output3').innerHTML = dates.join(',');
You can try mapping over the contents of dates instead, as so:
let datesElem = dates.map(date =>`<p>${date}</p>`);
// test: console.log(datesElem)
document.getElementById('output3').innerHTML = datesElem
I am calling a stored procedure 'ujo_get_id' by following code
new sql.Request()
.input('id', sql.Int, 0)
.input('fld', sql.VarChar(10), fld)
.execute('ujo_get_id').then(function( recordsets) {
console.log(recordsets[0][0]);
}.catch(function(err) {
// ... execute error checks
});
output of the console shows this { ' ': "some value" }
I want to store that(some value) value in a variable how can I do it because key is empty
I'm guessing the stored procedure has a select statement without an alias. If you can modify the stored procedure, add an alias and it shouldn't return an empty string for a key.
Something like this:
SELECT somefield
Should be changed to this:
SELECT somefield as someAliasName
If you don't have access to the stored procedure, try grabbing the key like this:
recordsets[0][0]['']
Did you try this?
console.log(recordsets[0][0][" "])
Or maybe another way if you know for sure that the stored procedure will give you only one result is converting the object into an array and checking first element:
var raw = recordsets[0][0]
var result = Object.keys(raw).map(k => raw[k])[0]
console.log(result)
My Setup:
What I'm doing is pulling a very large table from MySQL (40,000+ Rows)
SpoolInfo.request.query("SELECT SpoolNumber AS a, DrawingNumber AS b, LineSize AS c, PipeSpec AS d, CU AS e, SheetNumber AS f, FluidCode AS g FROM Job" + JobNumber + ".SpoolInfo ORDER BY SpoolNumber ASC");
Doing a simple operation to it to format it how it is needed for the application I have to send it to:
if(SpoolInfo.response.data){
SpoolInfoRowsObj = {"Cache":[]};
SpoolInfo.response.data.forEach(function(d,di){
SpoolInfoRowsObj.Cache.push(_.values(SpoolInfo.response.data[di]));
});
Then storing it back into a Cache table for quicker access:
(This is needed because I can't find a way to make the .forEach loop to run faster, and currently takes over 20 seconds.)
UpdateCacheTable1.request = new AP.MySQL.Request();
UpdateCacheTable1.request.execute("UPDATE `Job" + JobNumber + "`.`CacheTable_SpoolInfo` SET `SpoolInfoObj` = '" + JSON.stringify(SpoolInfoRowsObj.Cache) + "' WHERE ID = 1");
The Problem:
When I retrieve that data back later:
CacheSpoolInfo.request.query("SELECT SpoolInfoObj FROM Job" + GetJobNumber.response.data[0].JobNumber + ".CacheTable_SpoolInfo ");
CommRef_.SpoolInfo = CacheSpoolInfo.response.data
And try to use is like this:
....
}else if (t == "SpoolInfo"){
rowsObj = {"Rows":[]};
rowsObj = {"Rows":JSON.parse(CommRef_.SpoolInfo[0].SpoolInfoObj)};
}else{
....
It has a bunch of extra "\" stuff in it for all the special characters like:
"Rows": [
[
"[[\" 1-AII22-84042S01 \",\"1040\r\"],[\"0-A102-27564S01 \",\"110\r\"],.....
]
]
So of course the ouput is not the same JSON structured format that I saved.
I kinda thought using JSON.stringify() and JSON.parse() as I did would handle this.
My Question:
How can I handle this so the data I pull back can be handled the same way it would have been before I sent it to the DB?? AKA get rid of all the little slashes so JSON can parse it again.
The problem is that MySQL is adding the escapes when you save the string back in, because MySQL has no idea what JSON is and is storing it as a VARCHAR. An easy way to get around this is to do the escaping yourself before you store the string in the database.
For example, if you have a PHP backend, to store you would do
$escapedString = mysqli_escape_string($myJSONString);
// Store $escapedString in db
For, retrieval, you would then do
$escapedString = // query code
$myJSONString = stripslashes($escapedString);
How you handle the escape will vary based on your backend architecture. You might also consider using a database that has native support for JSON.
Another option would be to write a JavaScript function that does the stripping for you (there is no native function that does this). It should be doable with some regex. To see how you might go about this, see this existing SO question related to stripping slashes. Note that you'll need to change that a bit, since you only want to remove escape slashes while in that post the OP wants to remove all slashes (which is wrong for JSON since your data might actually contain slashes).
I have an array like this:
var people = [
'<option value=\'64\'>Tom',
'<option value=\'76\'>Dan',
];
I am looping through each item in the array to extract the value (like the number 64 in the first item) and the text (like Tom in the first item). I tried multiple ways of extracting these details from each item but I am unable to. I even tried using substrings and other methods. Can someone tell me how to extract this information?
You should use a regular expression in such a case.
For example:
var things = people.map(function(s){
return s.match(/(\d+)\W+(\w+)$/).slice(1)
});
This builds this array:
[ ["64", "Tom"], ["76", "Dan"] ]
You might want to adapt it for your precise needs:
check an array is returned by match, if some strings might be invalid
change the regex if the pattern is more variable
Note that you probably shouldn't have such an array to start with. If you generate it server-side, you should opt for the generation of a JSON structure instead and let the client script build the interface from the data, instead of building it from something which is neither clean data nor GUI.
You can use multiple split :
var str = '<option value=\'64\'>Tom';
var tmpStr = str.split("'");
var number = (tmpStr[1].split("\\"))[0];
var name = (tmpStr[2].split(">"))[1];
document.write(number + " " + name);
I have an initial array (users) with multiple (string and numeric) arrays therein:
var users = [
['User: 10792 - Jack',45.7546,-117.807,2,'/res/smR11.gif'], ['User: 11248 - John',38.0867,131.976,3,'/res/smR08.gif']
];
I have a string of data from our server in the current form of:
newData = "['User: 18469 - Gary',-33.9399732539481,151.164383805489,3,'/res/markerw.gif'],['User: 10020 - Robert',40.6437563454472,-73.7593346140851,6,'/res/smR10.gif']";
I erase all existing data with users.length = 0;
I then need to insert the newData into the users array.
NOTE: I can obviously modify the server data into any other format
that would be more suitable.
Any help would be greatly appreciated.
try something like this
var users = JSON.parse(newData);
Your newData string looks very similar to the javascript above it. How about this...
users = eval('[' + newData + ']');
[EDIT]
As Bergi, rajeshkakawat and StephenJames pointed out, eval will work but is less secure.
See: JSON.parse vs. eval()