JavaScript - Sending javascript object as a hidden input field - javascript

I have a JS Array of Objects as follows:
var tables = new Array();
var table = new Object();
table.no=1001;
table.name="Table-1";
tables.push(table);
table.no=1001;
table.name="Table-1";
tables.push(table);
Now I need to send this tables object-array through a hidden field in a form. Can I directly assign the value of hidden field as tables object.

use JSON.stringify() to convert it to JSON string and send your data.
side note:
There is an issue in the way you are creating an appending objects. Each time you are editing the same object. It will result in all the elemnts in your array being the last object you made as they are all references to the same object you have. resolve this by creating new objects when you append items to the array
var tables = new Array();
tables.push({"no":1000,"name":"Table-0"});
tables.push({"no":1001,"name":"Table-1"});
alert(JSON.stringify(tables));

You could stringify the value, put it in the field, send it to the server and then decode it. To stringify an object:
JSON.stringify(tables);
Assuming that you're using PHP on the server, you could decode it using json_decode function.

Related

How to push an object in a object - javascript

I have two ways to fill the same hidden input in a form
Using an import CSV button
Adding data using another inputs
When I use the first option, the hidden input is filled with this
for example:
correct data
[{"url":"http://www.restaurant.com","businessTypeId":"1"},{"url":"http://www.hotel.com","businessTypeId":"2"}]
and works correctly if I store this data
but when I use the second option, the input is filled with this:
incorrect data
{"url":"http://www.google.com","businessTypeId":"3"}
That's incorrect because it doesn't have [brackets] at the beginning neither at the end
Another problem is when I insert data and fill that hidden input (with the first way) and then I try to add more data using the second way,
I get this
[{"url":"http://www.restaurant.com","businessTypeId":"1"},
{"url":"http://www.hotel.com","businessTypeId":"2"}],
{"url":"http://www.google.com","businessTypeId":"3"}
the first 2 data was inserted using the first way, the third data was inserted using the 2nd way
all data should be inside those brackets []
how can I "open" the brackets to push new data and "close" them?
at the beginning of all the code, the variable starts like this
let placesArray = [];
after the first method, data is inserted using this
placesArray.push(JSON.stringify(csvResult));
document.getElementById('places').value = placesArray;
them, after the second method, data is inserted using this
placesArray.push(JSON.stringify(placeData));
console.log('placeData datatable ' + placeData);
document.getElementById('places').value = placesArray;
Note: if I use the first method two times, brackets are duplicated, like this
[{"url":"http://www.restaurant.com","businessTypeId":"1"}
{"url":"http://www.hotel.com","businessTypeId":"2"}],
[{"url":"http://www.beauty-shop.com","businessTypeId":"3"},
{"url":"http://www.dentist.com","businessTypeId":"5"}]
I definitely need to "open" the object so that I can insert the new data and not go through this, how could I do that?
In the console.log, I have this for placeData [object Object], same result for csvResult, both are object
You could flatten the array before every value set
placesArray = placesArray.flat()
document.getElementById('places').value = placesArray;
Seems like csvResult is itself an array and as you stringify it and push it to placesArray, it doesn't look like the result you want.
I'd go with this instead
placesArray.push(...csvResult) // push each `csvResult` item into `placesArray`
document.getElementById('places').value = JSON.stringify(placesArray)
SOLVED:
I erased all JSON.stringify and added it to every line when I push data into inputs
like this
document.getElementById('places').value = JSON.stringify(placesArray);
in all lines when this is used.
thanks to #hgb123
for prevent to accumulate [brackets[more brackets]] I used .flat()
placesArray = placesArray.flat()
document.getElementById('places').value = JSON.stringify(placesArray);

array object with empty field name

In node-red i have array object in msg.payload.
the array object is [{"":"This Pallet ID is already in Pick Request List"}]
The array object has empty field name. please suggest how to retrieve value form the array.
I have tried msg.payload[0][0], msg.payload[0].Value. But not working
What you need is
var text = msg.payload[0][""];
Works in Chrome at least...

Show Json Object In TextBox

I have json returned from Database.I want to pick only one object Value and show it in the textbox. Here is my json.
[{
"ErrorMessage":"",
"ID":294,
"ExpenseID":0,
"EffectiveDate":"/Date(1262284200000)/",
"FormattedEffectiveDate":"01-01-2010",
"Perunit":null,
"VATRate":17.5,
"ChangedByID":1,
"ChangedByName":"superuser, superuser",
"Expense":null,
"ErrorSummary":null,
"ErrorList":[]
}]
I have Tried
var Jsoninvoice = JSON.stringify(data)
alert(Jsoninvoice.VATRate) and also alert(data.VATRate)
Thank you In advance.
You have an array containing 1 object. stringify turns this object into a string - you need it parsed so you can use it.
(I'm not sure if the object is parsed already, so to cover all bases, we'll parse it)
var Jsoninvoice = JSON.parse(data);
alert(Jsoninvoice[0].VATRate);
You have to specify the arrays index before you can access the properties.
It is already json object and stringify is not needed as #tymJV said you need to parse it if it is returned as string, just you need to access array item, as it is an array:
alert(data[0].VATRate)
SEE FIDDLE
You could use $.parseJSON(YOURJSON), and then use the keys to pull the data. Since it's in an array, you'll have to use [0] to pull the first item in the array (ie: your data).
Example
$(document).ready(function(){
var j ='[{"ErrorMessage":"","ID":294,"ExpenseID":0,"EffectiveDate":"/Date(1262284200000)/","FormattedEffectiveDate":"01-01-2010","Perunit":null,"VATRate":17.5,"ChangedByID":1,"ChangedByName":"superuser, superuser","Expense":null,"ErrorSummary":null,"ErrorList":[]}]';
var json = $.parseJSON(j);
alert("VATRate: "+json[0].VATRate);
});
Fiddle for reference

Parse codebird reply into a array (or acces to the json text into the codebird's reply)

I am trying to use codebird to get some data from twitter. I have a script in JavaScript.
My problem is that codebird's reply is an object and not a JSON. So I can't use eval() to get parse the json text in an array.
I just need to acces the json data.
Thank you in advance
var cb = new Codebird();
cb.setConsumerKey("", "");
cb.setToken('','');
cb.__call(
"search_tweets",
"q=Twitter",
function (reply) {
data = eval(reply) //parse the returned JSON to array
}
}
);
If you need to convert a JavaScript object into a JSON string you can use
data = JSON.stringify(reply)
But usually it's better to deal with object itself - e.g. you can iterate thru it's properties (creating your own array if needed)

How can I set my data as JSON in a hidden input field

I have an input field like the one below
<input type="hidden" value="" id="inputField">
Now I have list of products and for each product I have a checkbox. When a user clicks on the checkbox, I get the product id and name. Now I want to save it again in the hidden field like below
<input type="hidden"
value="[{"product_id":123,"name":"stack"},{"product_id":456,"name":"overflow"}]"
id="inputField"
>
My first question is how I can do this and how can I create the JSON?
Secondly if the user again unchecks a product checkbox then I need to get the current hidden value and convert it into some data structure, remove the unchecked box id from the data structure and then save it again in the hidden field.
Is there any library which does this job in JavaScript?
Using jQuery:
HTML:
<input type="hidden" value='[{"product_id":123,"name":"stack"},{"product_id":456,"name":"overflow"}]'
id="inputField">
JS:
var data = {}
data.products = jQuery.parseJSON($('#inputField').val())
alert(data.products[0].product_id)
The building block that you look for are JSON.stringify and JSON.parse;
var stringData = '[{"product_id":123,"name":"stack"}, {"product_id":456,"name":"overflow"}]';
// Convert a string to an JavaScript object
var arrayData = JSON.parse(stringData);
// Convert a JavaScript object to a string
stringData = JSON.stringify(arrayData);
Now, whenever one of your checkboxes changes state, you'd get the object from the hidden field and modify it. After the modification of the object, you'd save the string back to the hidden field.
To read and store the value from/to the hidden field:
var field = document.getElementById('inputField');
// Reading the value
stringData = field.getAttribute('value');
// Storing the value
field.setAttribute('value', stringData);
You still lack the modifications of your array which you would do similar to:
// Adding a newly checked product
arrayData.push({
product_id: …,
name: …
});
// Removing a product from the list is more complicated
arrayData = arrayData.filter(function(product){
var productIdToRemove = …;
return product.product_id!==productIdToRemove;
});
Regarding libraries: Probably most do contain code to facilitate array manipulation and setting of form data. See the documentation of jQuery or prototype or the other answers for examples.
Just a thought: Wouldn't it be simpler to discard the whole idea of using the hidden field and transfer the checkboxes to the server instead. If the checkbox was checked, use it, otherwise ignore the correlating product data.
In JavaScript, just assign the value:
var json = JSON.stringify([{"product_id":123,"name":"stack"}]);
document.getElementById('inputField').setAttribute('value', json);
In a server-side language, encode the JSON in HTML, for example with php's htmlspecialchars or python's html.escape. The result will look like this:
<input type="hidden" id="inputField"
value="[{"product_id":123,"name":"stack"}]">
As it is stated in other answers below, to convert JSON to string, use JSON.stringify() function like so:
var json = JSON.stringify([{"product_id":123,"name":"stack"}]);
document.getElementById('inputField').setAttribute('value', json);
And you get string representation of JSON object in var json. To do this other way round so you can update the actual JSON object contained in that string, you can use eval:
var json_object = eval("("+json+")");
Now, original JSON object is recreated, and you can update it, and re-strigify it back to hidden field or some other var...
I am still a bit confused about your question, but if you are simply storing the name and id from the input checkboxes which are checked you can do this quite simply using jQuery.
var jsonArray = [];
$("input:checkbox:checked").each(function(){
var jsonObj = {};
jsonObj.product_id = $(this).attr("id");
jsonObj.name = $(this).attr("name");
jsonArray.push(jsonObj);
});
The variable jsonArray will now hold a json string similar to the example you have posted. You can use JSON.stringify(jsonArray) to see this.
There is no need to create the hidden field, holding this string as the value and trying to add and remove from it as checkbox states change. Simply execute the javascript when the page is ready to change via button click, etc.
Best of luck.
I would suggest to use the encodeURIComponent function. Together with the JSON.stringify we should have something like the following:
var data= "{"name":"John"}";
var encodeddata encodeURIComponent(JSON.stringify(var data= "{"name":"John"}";
))
Now that value can be safely stored in an input hidden type like so:
<input type="hidden" value="'+encodeddata+'">
Now to read the data back we can do something like:
var data = JSON.parse(decodeURIComponent(value))
If you have a JSON object, save it to the hidden field using JSON.stringify:
var myObj = [{"product_id":123,"name":"stack"},{"product_id":456,"name":"overflow"}];
document.getElementById('inputField').value = JSON.stringify(myObj);
Add library
"<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>"
Use: ${fn:escapeXml(string1)}
input type="hidden" value="${fn:escapeXml(string1)}" id="inputField"

Categories