How to fetch dynamic form data to mail using jquery

To fetch dynamic form data using jQuery and send it via email, you can follow these steps:

Step 1: Get the form data using jQuery

Use the serialize() method to get the form data as a string. This method serializes the form elements into a string in the format key=value&key=value.

var formData = $('#myForm').serialize();

Replace #myForm with the ID of your form.

Step 2: Prepare the email data

Create a JavaScript object to hold the form data. You can use the JSON.parse() method to convert the serialized form data into a JSON object.

var emailData = {};
emailData.formData = JSON.parse(formData);

Step 3: Set up the email

Use a library like jQuery Email or EmailJS to send the email. You can also use the built-in mailto protocol to send the email, but it may not work in all browsers.

var email = {
  to: '[email protected]',
  subject: 'Form Submission',
  body: ''
};

// Add the form data to the email body
email.body += 'Form Data:\n';
$.each(emailData.formData, function(key, value) {
  email.body += key + ': ' + value + '\n';
});

Step 4: Send the email

Use the email library or the mailto protocol to send the email.

// Using jQuery Email
$.email.send(email);

// Using EmailJS
EmailJS.send({
  to: email.to,
  subject: email.subject,
  body: email.body
});

// Using mailto protocol
window.location.href = 'mailto:' + email.to + '?subject=' + email.subject + '&body=' + email.body;

Here's the complete code:

$('#submitForm').on('click', function() {
  var formData = $('#myForm').serialize();
  var emailData = {};
  emailData.formData = JSON.parse(formData);

  var email = {
    to: '[email protected]',
    subject: 'Form Submission',
    body: ''
  };

  email.body += 'Form Data:\n';
  $.each(emailData.formData, function(key, value) {
    email.body += key + ': ' + value + '\n';
  });

  // Send the email
  $.email.send(email);
  // or
  // EmailJS.send({
  //   to: email.to,
  //   subject: email.subject,
  //   body: email.body
  // });
  // or
  // window.location.href = 'mailto:' + email.to + '?subject=' + email.subject + '&body=' + email.body;
});

Make sure to replace #myForm with the ID of your form and [email protected] with the recipient's email address.