I have 5 forms that are generated by a foreach loop and I want to send the input data with jquery ajax. If I want to grab the values from the 2nd form, I got an empty array.
My form:
<form id="<?php echo $gb_id; ?>" action="" method="POST" role="form"> // $gb_id is unique id
<input class="hide-robot honeyname" name="honeyname" type="text" />
<input class="form-control email_from" name="email-from" type="email" value="">
<input class="form-control email_to" name="email-to" type="hidden" value="<?php echo $gb_email; ?>">
<input class="form-control email_subject" name="email-subject" type="text" value="">
<textarea rows="6" class="form-control custom-control email_message" name="email-message">
</textarea>
<button class="btn btn-primary float-right" type="submit" name="submit_email">Send</button>
</form>
Under each form, ( also in the foreach) there is my jquery ajax and looks like this:
$('#<?php echo $gb_id; ?>').on('submit', function(e){
e.preventDefault();
var honeyname = $(".honeyname").val();
var email_from = $(".email_from").val();
var email_to = $(".email_to").val();
var email_subject = $(".email_subject").val();
var email_message = $(".email_message").val();
$.ajax({
url: 'email.php',
type: 'POST',
data: {
honeyname:honeyname,
email_from:email_from,
email_to:email_to,
email_subject:email_subject,
email_message:email_message
},
success: function(data){
$('.result').html(data);
},
complete:function(){
$('body, html').animate({scrollTop:$('.result').offset().top}, 'slow');
}
});
});
And my php:
print_r($_POST);
$recipient = $_POST['email_to'];
$subject = $_POST['email_subject'];
$body = $_POST['email_message'];
$headers = 'MIME-Version: 1.0';
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
$headers .= 'From: '.$_POST['email_from'];
echo $_POST['email_from'].'<br />';
echo $recipient.'<br />';
echo $subject.'<br />';
echo $body.'<br />';
If i fill the first form, i get a full array with all the values.
But if i fill in the second or third form, only [email_to] has a value and print_r gives me this output:
Array ( [honeyname] => [email_from] => [email_to] => steven@live.nl [email_subject] => [email_message] => )
So i thought: grab the closest values from the input fields like this in my jquery:
var honeyname = $(this).closest(".honeyname").val();
var email_from = $(this).closest(".email_from").val();
var email_to = $(this).closest(".email_to").val();
var email_subject = $(this).closest(".email_subject").val();
var email_message = $(this).closest(".email_message").val();
But now, i got a complete empty array, even with the first form!
How can i make this work for each form?
The $gb_id are unique and correspond with each other