405 error with Ajax POST / Nginx configuration

泄露秘密 提交于 2019-12-11 16:39:31

问题


I'm trying to send email with an Ajax form and swiftmailer. It works in local but not in production.

When contact_me.php takes parameters not from form but written explicitly the email is sent even from the server so I think Swiftmailer is working.

contact_me.js

// Contact Form Scripts

$(function() {

    $("#contactForm input,#contactForm textarea").jqBootstrapValidation({
        preventSubmit: true,
        submitError: function($form, event, errors) {
            // additional error messages or events
        },
        submitSuccess: function($form, event) {
            event.preventDefault(); // prevent default submit behaviour
            // get values from FORM
            var name = $("input#name").val();
            var email = $("input#email").val();
            var phone = $("input#phone").val();
            var message = $("textarea#message").val();
            var firstName = name; // For Success/Failure Message
            // Check for white space in name for Success/Fail message
            if (firstName.indexOf(' ') >= 0) {
                firstName = name.split(' ').slice(0, -1).join(' ');
            }
            $.ajax({
                url: "././mail/contact_me.php",
                type: "POST",
                data: {
                    name: name,
                    phone: phone,
                    email: email,
                    message: message
                },
                dataType: "text",
                cache: false,
                success: function() {
                    // Success message       
                },
                error: function() {
                    // Fail message                    
                },
            });
        },
        filter: function() {
            return $(this).is(":visible");
        },
    });

    $("a[data-toggle=\"tab\"]").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
    });
});


/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
    $('#success').html('');
});

contact_me.php

<?php
// Autoload for swiftmailer
require_once '../vendor/autoload.php';

// Check for empty fields
if(empty($_POST['name'])      ||
   empty($_POST['email'])     ||
   empty($_POST['phone'])     ||
   empty($_POST['message'])   ||
   !filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
   {
   echo "No arguments Provided!";
   return false;
   }


$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));

// Create the email and send the message
$email_subject = "TrustPair nouveau contact :  $name";
$email_body = "New form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nPhone: $phone\n\nMessage:\n$message";

// Add here swiftmailer code, need to return true
// Create the Transport
$transport = (new Swift_SmtpTransport('mail.gandi.net', 465, "ssl"))
  ->setUsername('name@domain.com')
  ->setPassword('password')
;

// Create the Mailer using your created Transport
$mailer = new Swift_Mailer($transport);

// Create the message
$message = (new Swift_Message())
    // Give the message a subject
    ->setSubject($email_subject)
    // Set the From address with an associative array
    ->setFrom(['noreply@domain.com' => 'Domain no reply'])
    // Set the To addresses
    ->setTo(['firstmailto@gmail.com', 'secondmailto@gmail.com'])
    // Give it a body
    ->setBody($email_body)
    ;

// Send the message
$result = $mailer->send($message);
echo $result;
// result is equal to the nbr of message recipients

if ($result == 0) {
    return false;
} else {
    return true;
}


?>

回答1:


Nginx server doesn't allow POST request with static page (ie. *.html).

There are hacks to handle the problem. In my case, it fix the 405 error but the emails weren't send.

The solution was to change the index.html to index.php, be sure to adapt your Nginx configuration to reflect this changes.



来源:https://stackoverflow.com/questions/44612803/405-error-with-ajax-post-nginx-configuration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!