Reputation: 4297
I have this:
<input type="text" name="field1" id="firstField">
<input type="text" name="field2" id="secondField">
<button name="submitButton" data-parameter="">Click</button>
When you click on the button, an EventListener (jQuery.on
) calls a function jQuery.ajax()
to load another page where the data gets processed.
the data-parameter
attribute is the data for $_POST
.
So, data-parameter="name1=test"
is $_POST["name1"]
with a value test
But how do I get the values of the input
-fields into this attribute?
And I have more than one form like this. Some contain more fields, some less.
Upvotes: 0
Views: 297
Reputation: 71
i don't know why cant you just send the data from those input fields directly to the $ajax().
Anyway a generalized code to get all data and to place it in on the data-parameter would be.. step 1: First you need a form or div tag binding all the necessary input fields and a button. step 2: I expect the variable name used in the url post method is same as the input field name, so the just the value changes. And also as u said if the no. of fields changes, its ok. even though u can use this piece of code. Step 3: i am using onclick event of the button to capture all data. And only after that u should run the code to send via $_POST Step 4: Change the tags #yourFormID,#buttonID as per use.
var data-parameter="";
$('#buttonID').click(function(){
$('#yourFormID input[type=text]').each(function(){
var data-parameter+=$(this).attr("name")+"="+$(this).val()+"&";
});
$('#buttonID').attr("data-parameter",data-parameter);
}
Upvotes: 1
Reputation: 5381
$('form button[name="submitButton"]').click(function(){
$(this).data('parameter',$(this).closest('form').serialize());
}
Upvotes: 1
Reputation: 70
The easiest way is to call var serializedFormData = $(yourform).serialize() and paste this data to your button $('[name=submitButton]').data('parameter', serializedFormData). You better provide a part of code to better understanding.
Upvotes: 0