Reputation: 183
I've a form with data repeated:
<form action="" method="post" id="myForm">
<?php foreach ($array as $value) { ?>
<input type="text" name="myInput[]" id="myInput" value="<?php $value->data1 ?>"/>
<textarea name="myTextArea[]" id="myTextArea"><?php $value->data2 ?></textarea>
<?php } ?>
<a href="#" id="submit">save</a>
</form>
I try to save values with ajax with this script:
jQuery(function(){
jQuery("#submit").click(function(e){
e.preventDefault();
var formData = {
'myInput' : jQuery('input[name=myInput]').val(),
'myTextArea' : jQuery("textarea#myTextArea").val()
};
jQuery.ajax({
url : 'someUrl',
type : 'POST',
data : formData,
dataType: 'json',
encode : true,
success: function(response){
if (response.success==true) {
}
else {
}
}
});
});
});
When data is not repeated (no array values) i've no problem, but in this case something goes wrong. Anyone could help me?
Upvotes: 0
Views: 419
Reputation: 1342
As suggested, use
data: $(this).serialize()
in your jQuery submit function. Leave the square brackets in the input names intact. In your PHP, you will be able to access your data like this:
$myInputs = $_POST['myInput'];
$myTextAreas = $_POST['myTextArea'];
Both variables will be arrays of values retrieved from the form. More info on PHP arrays is available here.
EDIT: If you need the value of $myInputs as a string separated by commas (e.g., "value1, value2, value3..." instead of array with "value1" etc.), you could do the following right after:
$myInputs = implode(', ', $myInputs); // this will convert the array to a string
Upvotes: 1
Reputation: 3515
Try this jQuery code :
jQuery(function(){
jQuery("#submit").click(function(e){
e.preventDefault();
var formData = $("#myForm").serialize();
jQuery.ajax({
url : 'someUrl',
type : 'POST',
data : formData,
dataType: 'json',
encode : true,
success: function(response){
if (response.success==true) {
}
else {
}
}
});
});
});
Please refer this answer to add multiple textbox values in database : Adding multiple textbox entry to a mysql database
Upvotes: 0