-4

I have no idea how php works. Im using JavaScript for every logic but its only for client use and php is for server i think. Im getting a 405 (Method Not Allowed) error.

How can i send a email (Example: "example@gmail.com") to myself with the input data from a html form?

//** IF u need it **

// Working Contact Form
$('#contact-form').submit(function() {
  var action = $(this).attr('action');

  $("#message").slideUp(750, function() {
    $('#message').hide();

    $('#submit').before('').attr('disabled', 'disabled');

    $.post(action, {
        name: $('#name').val(),
        email: $('#email').val(),
        comments: $('#comments').val(),
      },
      function(data) {
        document.getElementById('message').innerHTML = data;
        $('#message').slideDown('slow');
        $('#cform img.contact-loader').fadeOut('slow', function() {
          $(this).remove()
        });
        $('#submit').removeAttr('disabled');
        if (data.match('success') != null) $('#cform').slideUp('slow');
      }
    );

  });

  return false;

});

// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
  'use strict'
  window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation')

    // Loop over them and prevent submission
    Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        console.log("test")
        if (form.checkValidity() === false) {
          event.preventDefault()
          event.stopPropagation()
        }
        form.classList.add('was-validated')
      }, false)
    })
  }, false)
}())
//Ignore CSS, doesnt matter
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="php/contact.php" name="contact-form" id="contact-form">
  <div class="row">
    <div class="col-lg-6">
      <div class="row">
        <div class="col-lg-12 col-md-6">
          <div class="form-group">
            <input name="name" id="name" type="text" class="form-control border rounded" placeholder="Name :">
          </div>
        </div>
        <!--end col-->
        <div class="col-lg-12 col-md-6">
          <div class="form-group">
            <input name="email" id="email" type="email" class="form-control border rounded" placeholder="Email :">
          </div>
        </div>
        <!--end col-->
        <div class="col-lg-12">
          <div class="form-group">
            <input name="subject" id="subject" class="form-control border rounded" placeholder="Betreff :">
          </div>
        </div>
        <!--end col-->
      </div>
      <!--end row-->
    </div>
    <!--end col-->

    <div class="col-lg-6">
      <div class="form-group">
        <textarea name="comments" id="comments" rows="4" class="form-control border rounded" placeholder="Nachricht :"></textarea>
      </div>
    </div>
    <!--end col-->
  </div>
  <!--end row-->
  <div class="row">
    <div class="col-sm-12 text-right">
      <input type="submit" id="submit" name="send" class="submitBnt btn btn-pill btn-custom" value="Senden">
      <div id="simple-msg"></div>
    </div>
    <!--end col-->
  </div>
  <!--end row-->
</form>
<!--end form-->

Im using VS-Code with LiveServer extension to create a website. Can i use php there or what is the problem? Btw, still have a problem with JS i think..?!

If anybody know how to help, please comment! Thank you.

rioV8
  • 24,506
  • 3
  • 32
  • 49
RoyBlunk
  • 91
  • 8
  • @MarkOverton No it doesnt. Ive already seen this post. My problem is, that im getting a 405 (Method Not Allowed) error and i dont know how to solve this. – RoyBlunk Feb 05 '20 at 10:22
  • 1
    Then the address to which you send the `$.post` request on does not allow the `POST` method. Instead try the `GET` method, or allow `POST`. But it is hard to see what is happening if we can't take a look at your PHP. – Emiel Zuurbier Feb 05 '20 at 10:26
  • @EmielZuurbier Thank you for the hint. THe problem is, ive never used php before. I dont know how to use this but on some other stackoverflow.com sites they say, i can use this: ` ` and thats why i added the js so you may can tell me how to write it correctly. – RoyBlunk Feb 05 '20 at 10:28

1 Answers1

1

Every .php file opens with the <?php keyword. It indicates that this file contains PHP code. HTML can be used in PHP files so there is no different file type for that. Close the php file with ?>.

You could also have single lines of PHP code in for example your HTML.

<?php $title = 'Hello World'; ?>
<h1><?php echo $title; ?></h1>

You'll need to collect the data that send to the server. PHP has global variables which are variables that are available everywhere in any file. For example the $_GET variable. If you use the GET method to send your data, then you will be able to read that data from the global $_GET variable in the file that you send it to.

$_GET is an associative array. So sent data is stored like so:

[
  'name' => '',
  'email' => '',
  'comments' => ''
]

Associative arrays are comparable to objects in JavaScript. They both have a key and a value. Check if a key is set with the isset() function in PHP.

Because you are allowing the user to send data it is important to sanitize their data. It can contain malicious code and should be treated as such until you have sanitized it. filter_var is a PHP function which can do that for you.

Now that you have your data and cleaned it you can use the mail function to send a mail to the an email address. The mail function returns a boolean based on if the mail was sent successfully.

Good luck!

<?php

/** 
 * Get all the send data from JS.
 * $_GET is a global PHP variable. It is an array
 * which contains the data sent with the GET method.
 */
$name     = isset($_GET['name']) ? $_GET['name'] : '';
$email    = isset($_GET['email']) ? $_GET['email'] : '';
$comments = isset($_GET['comments']) ? $_GET['comments'] : '';

/**
 * All data that a user can send must be treated as dirty.
 * Therefor it is important to filter all malicious characters
 * from the data. Otherwise you are open to vulnerabilities.
 */
$name     = filter_var($name, FILTER_SANITIZE_STRING);
$email    = filter_var($email, FILTER_SANITIZE_EMAIL);
$comments = filter_var($comments, FILTER_SANITIZE_FULL_SPECIAL_CHARS);

/**
 * Now the data is received and sanitized we can use it
 * to send an email with.
 */
$to      = $email; // The email address to send to.
$from    = 'sender@example.com'; // Your email address.
$subject = 'the subject'; 
$message = $comments; // I assume comments is the message. 
$headers = 'From: ' . $from . "\r\n" . 'Reply-To: ' . $from . "\r\n" . 'X-Mailer: PHP/' . phpversion(); 

/**
 * Send the email.
 * The mail() function returns a true or false based
 * on if the email was sent successfully.
 */
$mail_status = mail($to, $subject, $message, $headers);

/**
 * Send a message back to JS based on if the mail has beent sent or not.
 */
if ($mail_status === true) {
  return 'Mail has been sent';
} else {
  return 'Sending the mail has failed';
}

?>
Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32
  • One thing to add. I still got the 405 (Method Not Allowed) error in the console output. Is this a error because im using VS Code Live Server or how do i have to handle this one? – RoyBlunk Feb 05 '20 at 12:09
  • No, it is because you use `$.post` which, like the name suggests, uses the `POST` method to send your data from JS to PHP. Use the equivalent jQuery function for `GET` instead. It might even be called `$.get` ;) – Emiel Zuurbier Feb 05 '20 at 12:46
  • I changed the `$.post` to `$.get` but it still dont work. I dont receive any email from anything. The error message isnt there anymore, so this is good i think, now i got a other notification in vs-code: `live reload is not possible without body or head tag`. – RoyBlunk Feb 05 '20 at 13:46
  • Well, you gotta run PHP on a server of some kind. Can be local or hosted. Do research on how to setup your PHP server. Live-reload won't suffice. – Emiel Zuurbier Feb 05 '20 at 15:29