最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - POST method to send form data with AJAX without JQUERY - Stack Overflow

programmeradmin4浏览0评论

I have a script in js that sends the form data from one page to the server and it works well with a Jquery function but I would like to be able to do it without the use of Jquery. When I try without jQuery the form is sent but the mail arrives empty, without sender, without subject and without message. Thanks in advance.

script con jQuery (OK)

$("#contact-form").on("submit", function(event) {
   event.preventDefault();
   $.ajax({
     type: "POST",
     url: "php/email-sender.php",
     data: {
       name: $("#contact-form #name").val(),
       email: $("#contact-form #email").val(),
       subject: $("#contact-form #subject").val(),
       message: $("#contact-form #message").val()
     },
     dataType: "json",
     success: function(data) {
    console.log(“success”);
       } else {
          console.log(“error”);
       }
     },
     error: function() {
         console.log(“error”);
     }
   });
 });  

PHP script that receives the data

session_cache_limiter('nocache');    
header('Expires: ' . gmdate('r', 0));    
header('Content-type: application/json');      

$Recipient = '[email protected]'; // <-- Set your email here    

if($Recipient) {      

    $Name = $_POST['name'];  
    $Email = $_POST['email'];  
    $Subject = $_POST['subject'];  
    $Message = $_POST['message'];  
    if (isset($_POST['category'])) {  
        $Category = $_POST['category'];  
    }

    $Email_body = "";    
    if (isset($_POST['category'])) {  
        $Email_body .= "From: " . $Name . "\n" .  
        "Email: " . $Email . "\n" .  
        "Subject: " . $Subject . "\n" .  
        "Message: " . $Message . "\n" .  
        "Category: " . $Category . "\n";  
    } else {  
        $Email_body .= "From: " . $Name . "\n" .  
        "Email: " . $Email . "\n" .  
        "Subject: " . $Subject . "\n" .  
        "Message: " . $Message . "\n" .   
        "Enviado el " . date('d/m/Y', time());  
    }   

    $Email_headers = "";  
    $Email_headers .= 'From: ' . $Name . ' <' . $Email . '>' . "\r\n".  
    "Reply-To: " .  $Email . "\r\n";  

    $sent = mail($Recipient, $Subject, $Email_body, $Email_headers);  

    if ($sent){   
        $emailResult = array ('sent'=>'yes');  
    } else{  
        $emailResult = array ('sent'=>'no');  
    }  

    echo json_encode($emailResult);  

} else {  

    $emailResult = array ('sent'=>'no');  
    echo json_encode($emailResult);  

}  

Associated HTML

<form id="contact-form" role="form">
      <div class="form-group has-feedback">
        <input type="text" class="form-control" id="name" name="name"  placeholder="Nombre" required>
      </div>
      <div class="form-group has-feedback">
        <input type="email" class="form-control" id="email" name="email" placeholder="Correo electronico" required>
      </div>
      <div class="form-group has-feedback">
        <input type="text" class="form-control" id="subject" name="subject" placeholder="Asunto" required>
      </div>
      <div class="form-group has-feedback">
        <textarea class="box-msg" rows="6" id="message" name="message">     </textarea>
      </div>
      <div class="form-group has-feedback">
        <input type="submit" value="Enviar" class="submit-button btn btn-default">
      </div>
</form>  

Test1 without jQuery (does not work)

// Submit contactForm START
const contactForm = document.getElementById("contact-form");

contactForm.addEventListener("submit", function(event) {
  event.preventDefault();
  var request = new XMLHttpRequest();
  request.open("POST", "/php/email-sender.php", true);
  request.setRequestHeader(
    "Content-Type",
    "application/x-www-form-urlencoded; charset=UTF-8"
  );

  request.onreadystatechange = function() {
    if (request.readyState == XMLHttpRequest.DONE) {
      // request end.
      if (request.status == 200) {
        // success START
        console.log(request.response);
        // success END
      } else {
        // error START
        console.log("error");
        // error END
      }
    }
  };

  var formData = new FormData();
  data.append("name", document.getElementById("name").value);
  data.append("email", document.getElementById("email").value);
  data.append("subject", document.getElementById("subject").value);
  data.append("message", document.getElementById("message").value);
  request.send(formData);
});  

Test2 without jQuery (does not work)

var contactForm = document.getElementById("contact-form");

contactForm.addEventListener("submit", function(event) {
  event.preventDefault();
  var request = new XMLHttpRequest();
  request.open("POST", "/php/email-sender.php", true);
  request.setRequestHeader("Content-Type", "application/json;  charset=UTF-8");

  request.onreadystatechange = function() {
    if (request.readyState == XMLHttpRequest.DONE) {
      // request end.
      if (request.status == 200) {
        // success START
        console.log(request.response);
        // success END
      } else {
        // error START
        console.log("error");
        // error END
      }
    }
  };

  var data = {
    name: document.getElementById("name").value,
    email: document.getElementById("email").value,
    subject: document.getElementById("subject").value,
    message: document.getElementById("message").value
  };
  request.send(JSON.stringify(data));
});  

I have a script in js that sends the form data from one page to the server and it works well with a Jquery function but I would like to be able to do it without the use of Jquery. When I try without jQuery the form is sent but the mail arrives empty, without sender, without subject and without message. Thanks in advance.

script con jQuery (OK)

$("#contact-form").on("submit", function(event) {
   event.preventDefault();
   $.ajax({
     type: "POST",
     url: "php/email-sender.php",
     data: {
       name: $("#contact-form #name").val(),
       email: $("#contact-form #email").val(),
       subject: $("#contact-form #subject").val(),
       message: $("#contact-form #message").val()
     },
     dataType: "json",
     success: function(data) {
    console.log(“success”);
       } else {
          console.log(“error”);
       }
     },
     error: function() {
         console.log(“error”);
     }
   });
 });  

PHP script that receives the data

session_cache_limiter('nocache');    
header('Expires: ' . gmdate('r', 0));    
header('Content-type: application/json');      

$Recipient = '[email protected]'; // <-- Set your email here    

if($Recipient) {      

    $Name = $_POST['name'];  
    $Email = $_POST['email'];  
    $Subject = $_POST['subject'];  
    $Message = $_POST['message'];  
    if (isset($_POST['category'])) {  
        $Category = $_POST['category'];  
    }

    $Email_body = "";    
    if (isset($_POST['category'])) {  
        $Email_body .= "From: " . $Name . "\n" .  
        "Email: " . $Email . "\n" .  
        "Subject: " . $Subject . "\n" .  
        "Message: " . $Message . "\n" .  
        "Category: " . $Category . "\n";  
    } else {  
        $Email_body .= "From: " . $Name . "\n" .  
        "Email: " . $Email . "\n" .  
        "Subject: " . $Subject . "\n" .  
        "Message: " . $Message . "\n" .   
        "Enviado el " . date('d/m/Y', time());  
    }   

    $Email_headers = "";  
    $Email_headers .= 'From: ' . $Name . ' <' . $Email . '>' . "\r\n".  
    "Reply-To: " .  $Email . "\r\n";  

    $sent = mail($Recipient, $Subject, $Email_body, $Email_headers);  

    if ($sent){   
        $emailResult = array ('sent'=>'yes');  
    } else{  
        $emailResult = array ('sent'=>'no');  
    }  

    echo json_encode($emailResult);  

} else {  

    $emailResult = array ('sent'=>'no');  
    echo json_encode($emailResult);  

}  

Associated HTML

<form id="contact-form" role="form">
      <div class="form-group has-feedback">
        <input type="text" class="form-control" id="name" name="name"  placeholder="Nombre" required>
      </div>
      <div class="form-group has-feedback">
        <input type="email" class="form-control" id="email" name="email" placeholder="Correo electronico" required>
      </div>
      <div class="form-group has-feedback">
        <input type="text" class="form-control" id="subject" name="subject" placeholder="Asunto" required>
      </div>
      <div class="form-group has-feedback">
        <textarea class="box-msg" rows="6" id="message" name="message">     </textarea>
      </div>
      <div class="form-group has-feedback">
        <input type="submit" value="Enviar" class="submit-button btn btn-default">
      </div>
</form>  

Test1 without jQuery (does not work)

// Submit contactForm START
const contactForm = document.getElementById("contact-form");

contactForm.addEventListener("submit", function(event) {
  event.preventDefault();
  var request = new XMLHttpRequest();
  request.open("POST", "/php/email-sender.php", true);
  request.setRequestHeader(
    "Content-Type",
    "application/x-www-form-urlencoded; charset=UTF-8"
  );

  request.onreadystatechange = function() {
    if (request.readyState == XMLHttpRequest.DONE) {
      // request end.
      if (request.status == 200) {
        // success START
        console.log(request.response);
        // success END
      } else {
        // error START
        console.log("error");
        // error END
      }
    }
  };

  var formData = new FormData();
  data.append("name", document.getElementById("name").value);
  data.append("email", document.getElementById("email").value);
  data.append("subject", document.getElementById("subject").value);
  data.append("message", document.getElementById("message").value);
  request.send(formData);
});  

Test2 without jQuery (does not work)

var contactForm = document.getElementById("contact-form");

contactForm.addEventListener("submit", function(event) {
  event.preventDefault();
  var request = new XMLHttpRequest();
  request.open("POST", "/php/email-sender.php", true);
  request.setRequestHeader("Content-Type", "application/json;  charset=UTF-8");

  request.onreadystatechange = function() {
    if (request.readyState == XMLHttpRequest.DONE) {
      // request end.
      if (request.status == 200) {
        // success START
        console.log(request.response);
        // success END
      } else {
        // error START
        console.log("error");
        // error END
      }
    }
  };

  var data = {
    name: document.getElementById("name").value,
    email: document.getElementById("email").value,
    subject: document.getElementById("subject").value,
    message: document.getElementById("message").value
  };
  request.send(JSON.stringify(data));
});  
Share Improve this question asked May 3, 2018 at 10:38 NelsonNelson 651 gold badge1 silver badge4 bronze badges 6
  • Does the console yield any errors? – Script47 Commented May 3, 2018 at 10:39
  • what's wrong with using jquery ? – niceman Commented May 3, 2018 at 10:50
  • @niceman the script in jQuery works, but there is a tendency to not use jQuery, which is why I am trying to eliminate my dependency on jQuery. In fact, jQuery is no longer used to develop javascripts with Framework as VUE or ANGULAR although it is much more practical and I personally think it is quite efficient jQuery as its promise indicates "write me less and do more" but it is also real that convention is removing jQuery as dependency. Nothing personal, tried to follow trends. – Nelson Commented May 3, 2018 at 12:19
  • @Script47 the console does not produce errors, the form is sent but the mail arrives empty, without sender, without subject, without message. I think the problem is in the way in which the data is packaged to be sent but I can not detect the error. – Nelson Commented May 3, 2018 at 12:25
  • @Nelson there are some errors in your javascript and php code. please check my answer. – Robert Anthony S. Tribiana Commented May 3, 2018 at 12:45
 |  Show 1 more ment

1 Answer 1

Reset to default 13

Your first javascript will return error because the data object is not defined.

Try this one

        const contactForm = document.getElementById("contact-form");

            contactForm.addEventListener("submit", function(event) {
                
              event.preventDefault();
              
                var request = new XMLHttpRequest();
                var url = "/php/email-sender.php";
                request.open("POST", url, true);
                request.setRequestHeader("Content-Type", "application/json");
                request.onreadystatechange = function () {
                    if (request.readyState === 4 && request.status === 200) {
                        var jsonData = JSON.parse(request.response);
                        console.log(jsonData);
                    }
                };
                var name =  document.getElementById("name").value;
                var email = document.getElementById("email").value;
                var subject = document.getElementById("subject").value;
                var message = document.getElementById("message").value;
                
                
                var data = JSON.stringify({"name": name, "email": email, "subject": subject, "message": message});
     
              
                request.send(data);
     
            });  

</script>

Check this thread on how to receive json POST: Receive JSON POST with PHP

Then Try this to your PHP file

<?php
// Handling data in JSON format on the server-side using PHP
header("Content-Type: application/json");
// build a PHP variable from JSON sent using POST method
$v = json_decode(stripslashes(file_get_contents("php://input")));
echo json_encode($v);
?>

To access the object in your PHP file, use

$v->name;
$v->email;
$v->subject;
$v->message;

SCREENSHOT: https://s9.postimg/w1fc8266n/2018-05-03_20h37_08.gif

发布评论

评论列表(0)

  1. 暂无评论