I am trying to store digital signature in database via rails application.
I am using javascript plugin that will convert signature into JSON string. Next I pluck JSON string from params and stored in a variable. Now I want to regenerate the signature by giving the plucked JSON string to a reverse javascript function.
The reverse function works fine if I set a variable in javascript directly to the JSON string and pass it to the function. However it does not work when I assign the variable to my rails variable which stores JSON string. The value of JSON string is exactly the same in both cases.
In first case the typeof var shows obj.obj type correctly but in second case it shows as a string. I tired every trick to parse using JSON and Jquery but it does not work.
My rails controller :
#recipient_signature = params[:recipient_signature]
My view where I want to see generated signature using the JSON string.
var sig = "<%=#recipient_signature%>";
$(document).ready(function() {
$('.sigPad').signaturePad({displayOnly:true}).regenerate(sig);
});
The above case does not work even though the value in #recipient_signature is correctly formed JSON string.
But when I assign the same JSON string to sig like below it works...
var sig = [{"lx":55,"ly":25,"mx":55,"my":24},{"lx":55,"ly":25,"mx":55,"my":25}....'];
This JSON string is same as in #recipient_signature and shows up in <%=#recipient_signature%> correctly.
Javascript somehow does not recoganize it as an array in first case and does in second case... how to fix it?
You're wrapping your json in quotes and using the variable in html encoded form:
var sig = "<%=#recipient_signature%>";
Should be
var sig = <%=raw #recipient_signature%>;
Or you should parse the json:
var sig = JSON.parse('<%=raw #recipient_signature%>');
Remove the quotes. That is, change:
var sig = "<%=#recipient_signature%>";
to
var sig = <%=#recipient_signature%>;
That way when the browser receives it it will look like your second example that works.
Note that that isn't really using JSON, it is simply using your server-side code to output a JS array literal directly into the JS code.
My guess is your assignment to sig with double quotes around it is causing a problem - try single quotes.
Related
After hours of searching and testing I finally have decided to post a question.
I need to be able to make something like this to work with a function.
var myCSV = [1,3,5,6];
Currently, I can grab the CSV from the database as that is how it is stored, myColumn = 1,3,5,6. I can get it to pass as an AJAX success response but it seems to want to add quotes. I then tried to add JSON encode to my PHP side of things and JSON Parse to the success call but still cannot get the function to work. The end goal is to select checkboxes based off the csv value.
This works
var FilterArray = [1,3,5,6]; // Manually added these numbers as is for testing
$('#myForm').find('.checks').each(function () {
$(this).prop("checked", ($.inArray(parseInt($(this).val()), FilterArray ) != -1));
});
After trying to much to get my AJAX success response to work in the FilterArray, I decided to just pass it to an input value and work with it. However, cannot figure out how to not treat it as a string when I pass it to the function. Here is what I have tried.
In my getCSV.php I have at the end this
json_encode($foundCSV);
In my AJAX Success
var FilterArray = JSON.parse(response);
I have also tried it without the json_encode and just sending it to an input value which does not add quotes.
So in summary, how can I take a csv e.g. 1,3,5,6 stored value and pass it to a function that works as shown above?
Assuming you have your string in a variable, called response, and its value is "1,3,5,6", you can translate it into an array of integers with this:
response.split(',').map(e => parseInt(e))
and you can then pass the result of this to your function.
Sticking to your naming, the code should look like this:
var FilterArray = response.split(',').map(e => parseInt(e));
What the code does:
takes the response and split it by using the comma character as a delimiter
this will create an array of strings
for each string in that array, tries to parse it as an integer (an ID, i guess?)
Clarifying question: What does your $foundCSV look like on the PHP side, before you json-encode it? Is it an array or a string with comma-separated numbers? You might want to check with your developer tools/debugger what the Ajax response contains. It sounds like you have a string but expect an array.
If that's the case, you can create an array on the JS- or PHP-side. For the JS-side, consult #GregorioPalama's answer.
Alternatively, you could do this on the PHP-side, which might be shorter:
$response = explode(',', $foundCSV);
and then work with json_encode($response).
Hello I am doing a form and I used a populate method to fill a form out in jJQuery (Yes I know jquery is just a library) for testing. Now I save the data in the form using Json and Local Storage. Then I call back the object in local storage and use Json to turn it back into a string. The problem is the string will be the EXACT same as the string i hard coded into the populate method but when I put the string to replace it (so its always using current form saved data) it will not work correctly. I'm assuming it is something small.
This is my object called back from local storage and turned back into a string.
var myString = localStorage.getItem("all");
var myStringSave = JSON.stringify(myString); //my string
myStringSave will contain for example:
Name:'Joe',dateBirth:'01/02/1992'
Which is the exact same as my hard coded one. However hardcoded works
$('#frm').populate({Name:'Joe',dateBirth:'01/02/1992'})
But the one in the string will not work:
$('#frm').populate(myStringSave)
or
$('#frm').populate({myStringSave})
I have been looking at it for a few hours and it makes no sense. The string is the exact same as my hard coded one, so why does it not work? Thank you any help is greatly appreciated.
populate accepts a JSON as parameter, and you give it a string.
The basic form for using Populate is: $(selector).populate(JSON,
options)
Don't do :
var myString = localStorage.getItem("all"); // this IS a string (localStorage can't store anything else)
var myStringSave = JSON.stringify(myString); // you stringify a string
You can get your JSON back by using :
myJsonSave = JSON.parse( localStorage.all )
Then $('#frm').populate(myJsonSave) should work.
You can even do it all in one line :
$('#frm').populate( JSON.parse( localStorage.all ) )
I have code
data = "{isShowLoginPopup:true,newFavOfferId:1486882}";
I want to convert it into JS object (not in JSON) and use it in this way:
data.newFavOfferId = ...
How can I do this?
If your source is trusted, the simplest solution is to use eval :
data = eval('('+data+')');
If you don't trust the source, then you'd better specify what you can have and parse the string manually (not terribly hard if you have only one level of properties for example).
Another solution (depending on your real data) would be to change your data into JSON by inserting the missing quotes :
data = JSON.parse(datareplace(/({|,)\s*([^:,}{]+)\s*(:)/g,'$1"$2"$3'));
just remove the quotes
data = {
isShowLoginPopup:true,
newFavOfferId:1486882
};
Fiddle: http://jsfiddle.net/QpZ4j/
just remove quotes "" from the
data = "{isShowLoginPopup:true,newFavOfferId:1486882}";
DEMO
Whilst on the surface this looks like JSON data, it's malformed and therefore it does not work directly with JSON.parse(). This is because JSON objects require keys to be wrapped in quotes...
therefore:
"{isShowLoginPopup:true,newFavOfferId:1486882}"
as valid JSON should be:
"{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}"
So what you have there in fact IS a JavaScript object, not JSON, however the problem you have is that this is a JavaScript object as a string literal. If this is hard coded, then you need to just remove the " from the beginning and end of the string.
var data = {isShowLoginPopup:true,newFavOfferId:1486882};
If this object is serialized and requires transmission from/to a server etc, then realistically, it needs to be transmitted as a JSON formatted string, which can then be de-serialized back into a JavaScript object.
var data = JSON.parse("{\"isShowLoginPopup\":true,\"newFavOfferId\":1486882}");
This is for a gaming application.
In my game I want to save special effects on a player in a single field of my database. I know I could just put a refrence Id and do another table and I haven't taken that option off the table.
Edit: (added information) This is for my server in node not the browser.
The way I was thinking about storing the data is as a javascript object as follows:
effects={
shieldSpell:0,
breatheWater:0,
featherFall:0,
nightVision:0,
poisonResistance:0,
stunResistance:0,
deathResistance:0,
fearResistance:0,
blindResistance:0,
lightningResistance:0,
fireResistance:0,
iceResistance:0,
windResistance:0}
It seems easy to store it as a string and use it using effects=eval(effectsString)
Is there an easy way to make it a string or do I have to do it like:
effectsString=..."nightVision:"+effects.nightVision.toString+",poisonResistance:"+...
Serialize like that:
JSON.stringify(effects);
Deserialize like that:
JSON.parse(effects);
Use JSON.stringify
That converts a JS object into JSON. You can then easily deserialize it with JSON.parse. Do not use the eval method since that is inviting cross-site scripting
//Make a JSON string out of a JS object
var serializedEffects = JSON.stringify(effects);
//Make a JS object from a JSON string
var deserialized = JSON.parse(serializedEffects);
JSON parse and stringify is what I use for this type of storatge
var storeValue = JSON.stringify(effects); //stringify your value for storage
// "{"shieldSpell":0,"breatheWater":0,"featherFall":0,"nightVision":0,"poisonResistance":0,"stunResistance":0,"deathResistance":0,"fearResistance":0,"blindResistance":0,"lightningResistance":0,"fireResistance":0,"iceResistance":0,"windResistance":0}"
var effects = JSON.parse(storeValue); //parse back from your string
Here was what I've come up with so far just wonering what the downside of this solution is.
effectsString="effects={"
for (i in effects){
effectsString=effectsString+i+":"+effects[i]+","
}
effectsString=effectsString.slice(0,effectsString.length-1);
effectsString=effectsString+"}"
Then to make the object just
eval(effectsString)
I know that I can create an associative array like this:
var MyAssocArray = {'sky':'blue', 'grass':'green'};
And I am very fond of using this method.
What I would like to do and am having trouble with is this:
I have strings saved like this:
var MyString = "'sky':'blue', 'grass':'green'";
And I want to be able to do this now:
var MyAssocArray = {MyString};
When I try that - I get this error:
invalid object initializer
What am I doing wrong?
How can I achieve this?
I found a different solution using PHP and JavaScript. The associative array string is echoed in the JavaScript code:
var Multidimensional_Arr[Multidimensional_Array_Key_Name] = {<?php echo $String_Pulled_From_Database; ?>}; // i.e. 'sky':'blue', 'grass':'green'
// The same can be done for a one-dimensional array
var My_Single_Dime_Arr = {<?php echo $String_Pulled_From_Database; ?>}; // i.e. 'sky':'blue', 'grass':'green'
Use JSON -- it's serialized JavaScript Object Notation and is pretty close to what you're doing.
You'd need to do
var MyAssocArray = JSON.parse(MyString);
Also, JSON uses double quotes, not single quotes; if you use simple objects, you can probably write code to just replace ' with "" in your strings, but it's tricky if the strings contain double-quotes.
If you are using a browser that doesn't implement JSON.parse(), you can either use the implementation on the JSON website (see links at bottom of this page) or if you're using jQuery, there's jQuery.parseJSON().
Warning: Your solution has a security risk, unless you are sure the data in the database has been sanitized:
var My_Single_Dime_Arr = {<?php echo $String_Pulled_From_Database; ?>}
This is equivalent to a call to eval(); if your database string has any malicious code it can do bad things. This is one reason why JSON was invented -- it's easy to ensure that its contents are valid (and hence safe) before evaluated.
Your overall architecture, as you have presented it to us, is [data in database] -> server-side PHP -> client-side JavaScript. This is a classic example of serialized data. I realize you may have constraints to keep your system running without interruption, but a strict serialization format would make your system more secure.
If you are sure the data is safe, then you could do:
var MyAssocArray = eval('{' + MyString + '}');
You can't do that.
To achieve what you want, use the split() function to split your string into comma-separated tokens first. Then each token should further be split by the ':' character.
Then push the two tokens obtained by the last split as the key and the value of your associative array.