简体   繁体   中英

How to send object data through $POST from via ajax (from jQuery to vanilla JS)

I have this jQuery snippet I was using to send form data through an ajax request and have the php spit out some more jQuery to show a email was sent. I have most of the code down put I wont get a response through, no mail, no js error, and no php error.

Here is my html form:

<form id="contact-form" method="post">
  <label for="required_question" style="position:absolute; left:-10000px; bottom:auto; width:1px; height:1px; overflow:hidden;"></label>
  <label for="required_question2" style="position:absolute; left:-10000px; bottom:auto; width:1px; height:1px; overflow:hidden;"></label>
  <label for="name" style="position:absolute; left:-10000px; bottom:auto; width:1px; height:1px; overflow:hidden;">name</label>
  <label for="email" style="position:absolute; left:-10000px; bottom:auto; width:1px; height:1px; overflow:hidden;">email</label>
  <label for="subject" style="position:absolute; left:-10000px; bottom:auto; width:1px; height:1px; overflow:hidden;">email</label>
  <label for="text" style="position:absolute; left:-10000px; bottom:auto; width:1px; height:1px; overflow:hidden;">message</label>
  <label for="submit" style="position:absolute; left:-10000px; bottom:auto; width:1px; height:1px; overflow:hidden;">submit</label>

  <input tabindex="-1" name="required_question" placeholder="Required..." style="position:absolute; left:-10000px; bottom:auto; width:1px; height:1px; overflow:hidden;"></input>
  <input tabindex="-1" name="required_question2" placeholder="Required..." style="position:absolute; left:-10000px; bottom:auto; width:1px; height:1px; overflow:hidden;"></input>
  <input type="text" name="name" placeholder="Name..." required></input>
  <input type="email" name="email" placeholder="Email..." required></input>
  <input type="text" name="subject" placeholder="Subject..." required></input>
  <textarea name="text" placeholder="Enter your message here" required></textarea>
  <input type="submit" class="submit" value="Submit."></input>
</form>

and here is the jquery snippet:

$('#contact-form').on('submit', function() {

  $('#submit').val('Sending...');

  var  data = {};

  $(this).find('[name]').each(function(index, value) {
    data[$(this).attr('name')] = $(this).val();
  });
  $.post('/dss-assets/PHP/mailer.php', {term: data}).done(function(data) {
    $('body').append(data);
  });
    return false;
});

Heres what I have so far in my vanilla js:

document.getElementById('contact-form').addEventListener('submit', function(event){
  event.preventDefault();
  document.querySelector('input[type="submit"]').value = 'Sending...';
  document.querySelector('input[type="submit"]').blur();
  $disabled_inputs = document.querySelectorAll('input, textarea');
  for(i = 0; i < $disabled_inputs.length; i++){
    $disabled_inputs[i].disabled = true;
    $disabled_inputs[i].style.opacity = '.7';
  }

  var $data = {};

  this.querySelectorAll('input[name], textarea[name]').forEach(function($input) {
  $data[$input.getAttribute('name')] = $input.value;
  });
  console.log($data)

  inquriry_request = new XMLHttpRequest();

  inquriry_request.onload = function(){
    document.querySelector('body').append(inquriry_request.responseText)
  }

  inquriry_request.onerrror = function(){
    console.log({contactpage: $data})
  }

  inquriry_request.open('POST', '/dss-assets/PHP/mailer.php', true)
  // ---it seems my data type was wrong and thats why it wouldnt send---
  inquriry_request.setRequestHeader('Content-Type', 'multipart/form-data'); 
  inquriry_request.send({contactpage: $data});

});

and here is the mailer.php:

<?php
if(isset($_REQUEST['contactpage'])) {

$array = $_REQUEST['contactpage'];
//------required questions-----------------
$rq = $array['required_question'];
$rqtwo = $array['required_question2'];

if($rq != '' || $rqtwo != ''){
  $quo = '"';
  $input = "$quo input[name*='hmnvr'] $quo";
  echo "<script>
    console.log('uhhohh')
  </script>";
  exit();
};

  //----------sendmail-------------
  $headers = "From: Desert Sun Studio | Sal <sal@desertsunstudio.com>\r\n";
  $headers .= "MIME-Version: 1.0\r\n";
  $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
  $name = $array['name'];
  $email = $array ['email'];
  $subject = $array['subject'];
  $text = $array['text'];

  $msg ='Hello ' . $name .',<br><br>
  Thank you for submitting a message through https://www.desertsunstudio.com. This is just to confirm your message has
  been received, please allow up to 24 hours to receive a response. To follow up or add any additional information
  please <a href="mailto:sal@desertsunstudio.com">click here</a> or simply reply to this email.';

  $msg2= 'Hello sally, this is your lil mail bot:)) Looks like we got a message, lets take a looksie: <br><br>From: ' . $name .
  '<br><br>Contact email: ' . $email . '<br><br> Message: &quot;' . $text . '&quot;';





  if(@mail($email, 'Response to your recent inqury at Desert Sun Studio.', $msg, $headers) && @mail('sal@desertsunstudio.com', 'Looks like we have a potential client!', $msg2, $headers)){
    $quo = '"';
    echo "<script>
      console.log('sent')
    </script>";
    exit();
  } else {

  echo "<script>
    console.log('uhhohh')
  </script>";
  exit();
  }
};

?>

try FormData to send the entire form

Example:

$('#contact-form').on('submit', function() {
      $('#submit').val('Sending...');
      var data = new FormData(this);
      $.ajax({
        type: 'POST',
        url: '/dss-assets/PHP/mailer.php',
        processData: false,
        contentType: false,    
        data: data,
        dataType: "json",
        success: function(res) {
           $('body').append(res)
        },
        error: function() {
            alert("fail");
        }
      });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM