0

I'm using bootstrap 4 beta, and I have a form I've created in an html file, that has an external javascript file linked in it that creates the error messages, that then points to a php file on success. I'm also using this bootstrap validation plug in. When trying to view and test the form locally, I'm getting the "cross origin request" error. Here is a screenshot of the error Here is a screenshot of the error I've looked into what this means and have looked up questions in attempt to find something similar but nothing has answered my questions. Basically: is there a way to circumvent this by making the php internal (in the html) and making the javascript point to it? Or can I somehow combine the javascript and php into one external file?

AND (this may make my other questions irrelevant) will this problem go away once my site is hosted and not being viewed locally?

Here is my code for reference: html:

<div class="row">
    <div class="col-lg-12">
        <form id="contactForm" name="sentMessage" class="" novalidate>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <input class="form-control" id="name" type="text" placeholder="Your Name *" required data-validation-required-message="Please enter your name.">
                        <p class="help-block text-danger"></p>
                    </div>
                    <div class="form-group">
                        <input class="form-control" id="email" type="email" placeholder="Your Email *" required data-validation-required-message="Please enter your email address.">
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group">
                        <textarea class="form-control" id="message" placeholder="Your Message *" required data-validation-required-message="Please enter a message."></textarea>
                        <p class="help-block text-danger"></p>
                    </div>
                </div>
                <div class="clearfix"></div>
                <div class="col-lg-12 text-center">
                    <div id="success"></div>
                    <button id="sendMessageButton" class="btn btn-xl" type="submit">Send Message</button>
                </div>
            </div>
        </form>
    </div>
</div>

javascript:

$(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 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(' ');
      }
      $this = $("#sendMessageButton");
      $this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
      $.ajax({
        url: "contact_me.php",
        type: "POST",
        data: {
          name: name,
          email: email,
          message: message
        },
        cache: false,
        success: function() {
          // Success message
          $('#success').html("<div class='alert alert-success'>");
          $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
            .append("</button>");
          $('#success > .alert-success')
            .append("<strong>Your message has been sent. </strong>");
          $('#success > .alert-success')
            .append('</div>');
          //clear all fields
          $('#contactForm').trigger("reset");
        },
        error: function() {
          // Fail message
          $('#success').html("<div class='alert alert-danger'>");
          $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
            .append("</button>");
          $('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
          $('#success > .alert-danger').append('</div>');
          //clear all fields
          $('#contactForm').trigger("reset");
        },
        complete: function() {
          setTimeout(function() {
            $this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
          }, 500);
        }
      });
    },
    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('');
});

php:

<?php
// Check for empty fields
if(empty($_POST['name'])      ||
   empty($_POST['email'])     ||     
   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']));
$message = strip_tags(htmlspecialchars($_POST['message']));

// Create the email and send the message
$to = 'myemail@mydomain.com'; // Add your email address inbetween the '' replacing yourname@yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form:  $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nEmail: $email_address\n\nMessage:\n$message";
$headers = "From: noreply@mydomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply@yourdomain.com.
$headers .= "Reply-To: $email_address";   
mail($to,$email_subject,$email_body,$headers);
return true;         
?>
Ailis
  • 47
  • 12
  • I assume you're viewing the html file that's saved on your computer (maybe with a URL like `file://path/to/file.html`). If that's the case, you should be getting a different error, because you won't have a server running to handle the PHP request. If you're using a server to host the files, you should still be fine because the request is set to `"contact_me.php"` which will use the same domain as the HTML page. Bottom line is, I'm not sure why you'd be getting this error. Can you post the exact error message? – Sidney Sep 19 '17 at 00:54
  • https://stackoverflow.com/a/9866124/1064767 – Sammitch Sep 19 '17 at 00:55
  • @Sidney I've added a screenshot to my question of the error! and yes I'm viewing an html file that's saved on my computer. – Ailis Sep 19 '17 at 02:22
  • Interesting, the error says that's a cross origin request, even though you're accessing a different file on your computer. It also says that `file://` is not allowed to perform cross-origin requests, so this should be solved when you upload the files to a server and access them over HTTP or HTTPS. – Sidney Sep 19 '17 at 04:45

1 Answers1

0

Instead of directly to file :

file:///dir/x/y/z/a.js

load the file through http schemas (http / https) :

http://your-web-url/x/y/z/a.js

https://your-web-url/x/y/z/a.js

mrJ0ul3
  • 126
  • 7