简体   繁体   中英

Can't submit form without reloading page

I build a link shortener,just for fun! Everything works, but everytime I create a link and submit the form, the page reloads! I wanted to prevent that with onclick="return false;" but it didnt work.

<input class="submit" type="submit" value="Create!"  />

$('#contactForm').submit(function () {
    sendContactForm();
    return false;
}); 

But nothing works, the file is just stuck and doesn't do anything! What am I doing from ? This is the problem page https://viid.su PHP

   require("db_config.php");
       $uid = 1;
      $flink = $_POST['url'];
      if(!preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $flink)) {
        $html = "Error: invalid URL";
      } else {

        $db = mysqli_connect($host, $username, $password);
        $conn = new mysqli($host, $username, $password, $database);

          $id = substr(md5(time().$flink), 0, 5);
          if($conn->query("INSERT INTO `".$database."`.`link` (`id`, `flink`,`adonly`,`userid`) VALUES ('".$id."', '".$flink."','true','".$uid."');")) {
            $html = 'Your short URL is <a class="test" href="https://viid.su/'.$id.'">https://viid.su/'.$id.'</a>';
          } else {
            $html = "Error: cannot find database";
          }
        mysqli_close($db);
      }

You can submit a form without reloading the page by using something like an AJAX call.

JavaScript

$('#contactForm').submit(function (e) {
    e.preventDefault();        

    $.ajax({
           type: "POST",
           url: "path/to/your/script.php",
           data: $('#contactForm').serialize(), // Packs the form's elements
           success: function(data)
           {
               // Do something  here if the call succeeded
               alert(data);
           }
         });
}

HTML

<form id="contactForm">
    <input type="text" name="username" />
    <input type="text" name="email" />
    <input type="submit" value="Submit form" />
</form>

PHP

<?php

echo $_POST['username'];

?>

Something along those lines should work, and you don't need anything else, as you are already using jQuery.

您需要使用事件对象作为函数回调中的参数并调用event.preventDefault()

Just change the <input type="submit" /> into something like <button onclick="return false;" id="shortenLinkButton">Send</button> <button onclick="return false;" id="shortenLinkButton">Send</button>

Then with jQuery you can catch the even like this:

// This code will be usable after the page has fully loaded
$(document).ready(function(){
  // Catch the onclick event
  $('#shortenLinkButton').on('click', function() {
    // do something
    alert('clicked the button, do your ajax stuff here after retrieving the data from the input');
  });
});

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