如何使用ajax和php提交表单以避免页面刷新

时间:2017-06-10 14:53:55

标签: javascript php ajax

我试图在网页上提交一个表单,但我不希望页面刷新,我会通过很多教程,但仍然无法弄明白有人应该我请修复我的代码。

的index.php

<script src="profile.js"><script>
  <div class="sta">
    <form action="test.php" method="POST" id="sta">
      <input type="text" name = "sta" id="sta" placeholder="Status">
      <input id="submit" onclick="status()" type="button" value="save">
    </form>
  </div>
</script>

profile.php

<?php
  session_start();
  include 'db.php';

  if(isset($_SESSION['email'])){
    $eml = $_SESSION['email'];

    $sql = $con->prepare("update alert_users_account SET statu=? where email_phone=?");
    $sql->bind_param('ss',$_POST['sta'],$eml);
    $sql->execute();
    $sql->close();
  }
?>

profile.js

function status() {
  var sta = document.getElementById("sta").value;

  var dataString = 'sta1=' + sta;
  if (sta == '') {
    alert("Please Fill All Fields");
  } else {
    // AJAX code to submit form.
    $.ajax({
      type: "POST",
      url: "test.php",
      data: dataString,
      cache: false,
      success: function(html) {
        alert(html);
      }
    });
  }
  return false;
}

1 个答案:

答案 0 :(得分:0)

使用onclick="return status()"

添加回报
<input id="submit" onclick="return status()" type="button" value="save">

form.submit

中试用
<form action="test.php" method="POST" onsubmit="return status()" id="sta">
  <input type="text" name="sta" id="sta" placeholder="Status">
  <input id="submit" type="button" value="save">
</form>