Post Hidden Input Element Values to Controller? - javascript

I have a number of hidden input elements on my ASP.NET MVC page. They each hold an integer value. They are identified by $('table#ratings input[name=newReviewRatings]').
Is it possible to post the integers in those hidden input elements using $.post() so that the controller is passed an array of integers?
This is probably easier using a <form> element and simply posting the form. But is it possible to do it using jQuery?

You should be able to get your array using something like this.
var data = [];
$('table#ratings input[name=newReviewRatings]').each(function(){
data.push($(this).val());
});
$.post(url, data);

An ideal fit for this situation is using map like:
var data = $('#ratings input[name=newReviewRatings]').map(function(){
return $(this).val();
}).get();
// Post the data to the respective url
$.post(your_url, data);
The .map() method is particularly useful for getting or setting the value of a collection of elements.

Related

Is there a more concise way to POST a large number of input element values to an API?

I have an ASP.NET project that is currently making use of JQuery and Bootstrap to create a front-end. One part of this front-end involves the user filling out a form made up on 30+ input elements, which then needs to be submitted to a back-end API.
Usually if I needed to communicate with an API I would use JQuery's built in post() and post() methods, and constructing a query string to use within these methods.
However since there is a large amount of input elements associated with this form, I am hesitant to make use of this particular approach as it seems like a very messy and roundabout way to submit the data to the API.
Unfortunately the usual <input action="action.xx"> approach is not available to me in this particular situation, so submitting the form as a whole is not a possibility.
However I really don't want to do something like this below:
queryString =
"?input1=" + $("#input1").val() +
"&input2=" + $("#input2").val() ... //repeat for 30+ input elements
$.post(url + queryString, funtion(data){ ... });
Surely there must be a better way to go about solving this particular issue that doesn't involve creating an abhorrently large string and passing it through JQuery's post method?
Give every input a name attribute instead (the same name you want to use for the query string), and then call .serialize() on the form to generate the query string:
$('form').on('submit', function(e) {
e.preventDefault();
console.log($(this).serialize());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input name="inp1">
<input name="inp2">
<input name="inp3">
<button>submit</button>
</form>
Or, if you can't do that, and you want a shorter, less error-prone way of generating the string than what you're using now, iterate over an array of selectors and grab each's .val(), then join by &s:
const ids = ['input1', 'input2', 'input3'];
const queryString = ids.map(id => $('#' + id).val()).join('&');

Posting a form of variable length per jquery AJAX

I have a form where the user can add any number of input fields.
those are sent to a .php which returns a result out of those submitted.
that means I can't know the length of the $_POST beforehand (and I don't want to).
Everything I found so far works with manually entering the fields into the ajax request
// Get some values from elements on the page:
var $form = $( this ),
term = $form.find( "input[name='s']" ).val(),
url = $form.attr( "action" );
(from the jQuery api)
but that would only work if I know how many fields there would be.
I just want all the fields (no matter how much there were added) to be posted..
is it possible to loop through all fields?
or to just send the normal $_POST as it would be posted without ajax?
You want to use jQuery's .serializeArray() or .serialize() depending on how your PHP expects the data.
The difference is that .serializeArray() creates a JSON array while .serialize() creates standard URL-encoded key/value pairs.
If you want to send it via AJAX and you are using jquery .serialize() will make it much easier. You can put all of the inputs inside a form then use $(form).serialize() as the data.
Here is the jquery documentation for .serialize()
http://api.jquery.com/serialize/
var values = {};
$.each($('#myForm').serializeArray(), function(i, field) {
values[field.name] = field.value;
});
This way your value array will have all the fields in your form 'myForm'

how to access json data attribute

I have a data-attribute for several element that I'm using to store an ID and a value for each picklist values for each element. These will all be used to populate one field in a modal if one of the elements is edited.
I've added the ID and name for each option for each element into the data attribute like so:
{id:a0Dd000000RT1dOEAT,name:aa},{id:a0Dd000000RT1dPEAT,name:bb}, {id:a0Dd000000RT1dQEAT,name:cc},{id:a0Dd000000RT1dREAT,name:dd},{id:a0Dd000000RT1dSEAT,name:ee}
These represents 5 picklist options for one of the elements.
What is the syntax to extract each one? I've tried versions of:
$('#elementID').data('picklistvalues')[0].id
and its not working, any suggestions? I'm obviously far from a javascript expert.
You need to JSON.parse() the value that .data() returns; then you can work with the value as a full JavaScript object.
var data = $('#elementID').data('picklistvalues');
// the attr value in the OP is not quite valid JSON
var obj = JSON.parse('[' + data + ']');
var id = obj[0].id;
It looks to me that you need to place quotes around the "id" values. These are not quite numbers and will not likely parse as anything but strings.

How to get multiple "listKey" values from a Struts 2 <s:select>?

I have a code like this:
<s:select id="s" list="list" listKey="id" listValue="displayValue">
When I get the value from the object I'll always get the id.
How can I change the "listKey" value dinamically so I could get for example, the name of the object (supposing other of my attributes besides id is name ) instead always de id?
I was trying some code in jQuery like this:
function changeListKey(){
var id = $("#s").val();
$('#s').attr('listKey','name');
var name = $("#s").val();
document.write(name); // Only to test if I could get the value
}
When I execute it it doesn't seem to change the "lisKey" value so I could get another one, what would be the solution?
Thanks a lot in advance.
John Smith.
Why would you want to mix up what's used as the key value? That would make a mess on the server side.
In any case, listKey isn't an HTML attribute, it's a custom tag attribute, and is meaningless after the HTML has been rendered and sent to the client. You would need to iterate over the HTML select element's options collection and change the values on the options.
All this said, you'd be much better off doing any bizarre manipulations like this in the action itself, and exposing only the desired key/value pairs to the JSP, either in a list, or more easily, in a map. Using a map eliminates the need to provide listKey/listValue attributes--just use the map's key as the option text, and the value as the option's value.

binding nested json object value to a form field

I am building a dynamic form to edit data in a json object. First, if something like this exists let me know. I would rather not build it but I have searched many times for a tool and have found only tree like structures that require entering quotes. I would be happy to treat all values as strings. This edit functionality is for end users so it needs to be easy an not intimidating.
So far I have code that generates nested tables to represent a json object. For each value I display a form field. I would like to bind the form field to the associated nested json value. If I could store a reference to the json value I would build an array of references to each value in a json object tree. I have not found a way to do that with javascript.
My last resort approach will be to traverse the table after edits are made. I would rather have dynamic updates but a single submit would be better than nothing.
Any ideas?
// the json in files nests only a few levels. Here is the format of a simple case,
{
"researcherid_id":{
"id_key":"researcherid_id",
"description":"Use to retrieve bibliometric data",
"url_template" :[
{
"name": "Author Detail",
"url": "http://www.researcherid.com/rid/${key}"
}
]
}
}
$.get('file.json',make_json_form);
function make_json_form(response) {
dataset = $.secureEvalJSON(response);
// iterate through the object and generate form field for string values.
}
// Then after the form is edited I want to display the raw updated json (then I want to save it but that is for another thread)
// now I iterate through the form and construct the json object
// I would rather have the dataset object var updated on focus out after each edit.
function show_json(form_id){
var r = {};
var el = document.getElementById(form_id);
table_to_json(r,el,null);
$('body').html(formattedJSON(r));
}
A much simpler approach would be to accept a form submission and output the data in JSON format. That way, there is no need to bind variables.
The solution has arrived. JQuery now has plugins for data binding and templates.
http://www.borismoore.com/2010/09/introducing-jquery-templates-1-first.html
http://api.jquery.com/jQuery.template/
http://api.jquery.com/category/plugins/data-link/
There is another simple template engine that loads JSON data directly into the form. See http://plugins.jquery.com/project/loadJSON plugin. It works similar way as the one that Jack placed here but it uses plain HTML for template.
You can see instructions how to use it on the http://code.google.com/p/jquery-load-json/wiki/WorkingWithFormElements and live example on the http://jquery-load-json.googlecode.com/svn/trunk/edit.html?ID=17.

Categories

Resources