Posting a form of variable length per jquery AJAX - javascript

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'

Related

How to send a form with 2 values ​from javascript?

I have a form and I want from a javascript function to send the form to php with 2 variables that I have in that javascript function
function transfer(old_id){
var select = document.getElementById('trans');
var button = document.getElementById('send_id');
button.addEventListener('click',function(){
var selectedOption = select.value;
alert(selectedOption);
alert(old_id);
document.delete_user.submit();
});
}
I want this line (document.delete_user.submit ();) to send the variables to php: selectedOption and old_id
If you want the form to send the data, then you need to have a form control with the name you want and the value you want.
If the data exists only in a variable (and isn't already in a form field) then you need to put it in a form field.
Either set the value property of an existing one (which you can get with, for example, getElementById) or create a new one (you'd generally want to use a hidden input for this) and append it to the form.

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('&');

Access JSON that has been serialized and encoded

I have a form that I gather the inputs of and save in 1 hidden text field.
In order to do this I do the following:
$data = JSON.stringify($('#engraving_options'));
$serializedData = JSON.stringify($('#engraving_options').serializeObject());
$encodedData = $('#textField0').val(encodeURIComponent($serializedData));
$('#textField0').val($encodedData);
This puts the data in [Object object] and saves that to the database as I want it to.
My question is - on the other end (PHP) how do I access that information and have it display?
There are a few spots on a site I'm working on (in Prestashop) that now show '[Object object]', and I'd like to make it nicely display the information in the object.
The current PHP for one of those display sections is this:
{$customization.datas.$CUSTOMIZE_TEXTFIELD.0.value|replace:"<br />":" "|truncate:28:'...'|escape:'html':'UTF-8'}
How is the best way to make that section display the information in the Object programatically? What is the best way to dig into that Object?
If you want retrievable data you need to serialize all the inputs of the form.
Try
var formData = JSON.stringify($('#engraving_options').serializeArray());
$('#textField0').val(formData);
See serializeArray() docs

Most efficient way for JSON or JS object to be passed along with Form Data via AJAX POST to PHP

On the face, it may appear that this is a repeat question. Please note that I have read through all the related posts and did not find any definite answer and/or the issue here is very different. Even some direction to some post or material clarifying the issues with specificity would be helpful. I am not looking for spoon feeding.
Here is the issue:
I have a form and I have some other meta-data (for lack of a better term) to be sent to the server which consists of configuration parameters. These are required along with the form data to be processed by a PhP back-end and return some complex JS and HTML markup.
Admittedly I am not a regular user of JSON but my reading pointed to using JSON for the non-form data and have the form data serialized separately and assign it to another property, as in:
var ser_data = $(form_selector).serialize();
var meta_data = { //Just for example
name: 'John Doe',
age: 62,
address: '22 Park Avenue'
};
And then pass the data in .ajax as:
data_sent = data_sent = {'meta_data':meta_data, 'form_data':ser_data};
some_promise = $.ajax({
url : '../php/json_test.php',
dataType: 'json',
type : 'POST',
cache : false,
data : data_sent
});
On the PhP side, I have to navigate $_POST[] at multiple levels to get to the data. Also, the form data loses the implicit URL decoding.
Of course, one way could be to manually construct the serialized string to be appended to the form serialized string as in
form_data_serialized...&name='John doe'&age=62...
Am I on the wrong track all together? Is there an approach that is better and simpler? THANKS!
.serialize simply creates a param string, for example, foo=bar&foobar=2. with this in mind, adding your additional params is basic string concatenation.
var data_sent = $.param(meta_data) + "&" + ser_data;
Convert meta_data into a param string, then append your serialized form data to it.
Why not do this the other way around? Create your metadata as a JSON string and add it to a hidden input field in your form, then POST that. Your form data is decoded into $_POST and you can extract and decode your JSON metadata from there.

Post Hidden Input Element Values to Controller?

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.

Categories

Resources