简体   繁体   中英

Submitting form data with php with no page reload?

I have a contact form, on my personal portfolio webpage, made with PHP with a friends help (i'm a dummy when it comes to PHP.)

Although i have a problem with it. Whenever the submit button is pressed, and the mail is sent, it makes the page reload. How can i fix this?

I've copied (and changed the personal stuff) all my form, since i have no idea where or what to change:

 <?php // define variables and set to empty values $nameErr = $emailErr = $commentErr = $subject = ""; $name = $email = $comment = $subject = ""; if ($_SERVER["REQUEST_METHOD"] == "POST") { if (empty($_POST["name"])) { $nameErr = "Name is required"; } else { $name = input($_POST["name"]); } if (empty($_POST["email"])) { $emailErr = "Email is required"; } else { $email = input($_POST["email"]); // check if e-mail address is well-formed if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $emailErr = "Invalid e-mail format"; } } if (empty($_POST["subject"])) { $subjectErr = "Subject is required"; } else { $subject = input($_POST["subject"]); } if (empty($_POST["comment"])) { $commentErr = "Comment is required"; } else { $comment = input($_POST["comment"]); } } // MailGun cURL API // $curl_post_data=array( 'from' => "$name <$email>", 'to' => 'my@mail.com', 'subject' => $subject, 'text' => $comment, ); $service_url = 'mailgunlink.com'; $curl = curl_init($service_url); curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); curl_setopt($curl, CURLOPT_USERPWD, "api:key-123456789123456789abc"); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); $curl_response = curl_exec($curl); $response = json_decode($curl_response); curl_close($curl); // trim // function input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?> <section id="kontaktformular"> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post"> <div class="row" id="kontakt"> <div class="six columns"> <label>Full Name <span class="error">*<?php echo $nameErr;?></span></label> <input class="u-full-width" type="text" placeholder="Peter" name="name" id="navn"> </div> <div class="six columns"> <label>Your Email <span class="error">*<?php echo $emailErr;?></span></label> <input class="u-full-width" type="email" placeholder="Peter@Example.com" name="email" id="email"> </div> <label>Subject <span class="error">*<?php echo $subjectErr;?></span></label> <input class="u-full-width" type="text" placeholder="Design" name="subject" id="subject"> <label>Message <span class="error">*<?php echo $commentErr;?></span></label> <textarea class="u-full-width" placeholder="Whatever..." name="comment" id="besked"></textarea> </label> <input class="button-primary change" type="submit" value="Send"> </div> </form> </section> 

I hope the snippet is sufficient, even though it looks messy like this. If you need more information feel free to yell at me for it.

Also, bonus question. I need the submit button to also HIDE the form (display: none; -> #kontaktformular) and SHOW another div (display: block; -> #feedbackmsg)

Thanks in advance! The first question is the most important!

I'm pretty sure that this question has already been asked and answered multiples. Either way to do it you'll have to use AJAX which is pretty simple and one way to do it is.

<section id="kontaktformular">
  <form id="kontaktform" method="post">
    <div class="row" id="kontakt">
      <div class="six columns">
        <label>Full Name <span class="error">*</span></label>
        <input class="u-full-width" type="text" placeholder="Peter" name="name" id="navn">

      </div>
      <div class="six columns">
        <label>Your Email <span class="error">*</span></label>
      </div>
      <label>Subject <span class="error">*</span></label>
      <input class="u-full-width" type="text" placeholder="Design" name="subject" id="subject">
      <label>Message <span class="error">*</span></label>
      <textarea class="u-full-width" placeholder="Whatever..." name="comment" id="besked"></textarea>

      </label>
      <input id="kontaktform_input" class="button-primary change" type="submit" value="Send">
    </div>
  </form>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$("#kontaktform").submit(function(e) {
  e.preventDefault(); // avoid to execute the actual submit of the form.
  $.ajax({
         type: "POST",
         data: $(this).serialize(), // serializes the form's elements.
         success: function(data)
         {
         }
       });
});
</script>

Yes AJAX is the answer you are looking for in this case:

Add an ID to the submit button eg.

  <input class="button-primary change" id="Kontakt_Submit" type="submit" value="Send"> 

Then next in your js file write a similar code

    jQuery("#Kontakt_Submit").click(function () {
      //serialize the data, in simple terms for you to understand, it will
      // get all the input element name value, then this data will be sent as POST DATA
      var data = jQuery('form').serialize();
      console.log('data-->' + data);
      $.ajax({
        type: 'POST',
        dataType: "json",
        url: 'ajax.php',
        data: {
            check: 'Kontakt_Form',
            Kontakt_Form_Data: data
        },
        success: function (data) {
        }
    });
});

Next in your ajax.php file add this code

    if ($_POST['check'] == 'Kontakt_Form') {
         $result_array = array();
         $extracted_Array= array();                          // since we declared          both the variable names as "value" in JQuery
         parse_str($_POST['Kontakt_Form_Data'], $extracted_Array);
         $name= $extracted_Array['name'];
         $email= $extracted_Array['email'];
...//do the the other things what you need to do here, then enter in result array and return it for your output values if any.
}

Hope this will help you understand in a simple way to set up what you wanted.

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