dsfjnxjlbqv9812
2019-02-18 07:29 浏览 126

如何防止页面刷新? jQuery Ajax PHP

I have made a form where I submit new employee data to the database using jquery ajax and php. The data gets submitted and appears in the database, but how do I get it so the data will display on my page without the page refreshing?

I want the data to appear on the page without the page refreshing.

My problem: I can submit the data, but the page refreshes. If I make it so the page doesn't refresh, it won't submit the data.

    function createNewEmployee(){
require ('connection.php');
    $first = $_POST['first'];
    $last = $_POST['last'];
    $sin = $_POST['sin'];
    $pwd = $_POST['pwd'];
    $sql = "INSERT INTO employee (firstname, lastname, sin_, pass_) VALUES ('$first', '$last', '$sin', '$pwd');";
    mysqli_query($conn, $sql);
}




  <form id="addform" action="addemployee.php" method="POST">
<p>Add New Employee:<p>
    <input type="text" name="first" placeholder="First Name">
    <br>
    <input type="text" name="last" placeholder="Last Name">
    <br>
    <input type="text" name="sin" placeholder="SIN Number">
    <br>
    <input type="password" name="pwd" placeholder="Password">
    <br>
    <button type="button" id="submitbtn">Add</button>
    $(document).ready(function() {

  $("#submitbtn").click(function() {
    var first = $("#name").val();
    var last = $("#last").val();
    var sin = $("#sin").val();
    var pwd = $("pwd").val();

    $.ajax({
      type: "POST",
      data: {first:first,last:last,sin:sin,pwd:pwd},
      url: "addemployee.php",
      success: function(result) {
        $("#resultadd").html(response);
      }

    });
  });
});
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答 默认 最新

  • 已采纳
    duanou1904 duanou1904 2019-02-18 08:03

    Add return false; after your ajax request to prevent the page from refreshing.

    Code Snippet

    
    $(document).ready(function() {
      $("#submitbtn").click(function() {
        var first = $("#name").val();
        var last = $("#last").val();
        var sin = $("#sin").val();
        var pwd = $("pwd").val();
        $.ajax({
          type: "POST",
          data: {first:first,last:last,sin:sin,pwd:pwd},
          url: "addemployee.php",
          success: function(result) {
            $("#resultadd").html(response);
          }
    
    });
    
    return false; }); });
    

    点赞 评论 复制链接分享
  • douganmo1121 douganmo1121 2019-02-18 07:47

    Try this:

         success: function() {
          location.reload();
    window.location.href = "admin.php";
        }
    
    点赞 评论 复制链接分享
  • dqz84361326 dqz84361326 2019-02-18 08:17

    AJAX is a technology that was mainly developed to create more dynamic websites i.e. update parts of the webpage without a complete page refresh or server roundtrip.

    You can read basics here. https://www.w3schools.com/asp/asp_ajax_intro.asp

    You`re using jQuery AJAX requests in JavaScript. So you can send and request data without blocking or refreshing the page. Also you are passing a success function with your AJAX request which will be executed asynchronously when the response arrives.

    Your goal now is to create a PHP web service that sends a response body with your newly created employee and a correct http response code, indicating if the insertion was successful.

    See the solutions stated here to get started in php web services:

    php web service example

    and read about CRUD and REST like here:

    https://www.cloudways.com/blog/execute-crud-in-mysql-php/ https://www.codeofaninja.com/2017/02/create-simple-rest-api-in-php.html

    Use the response in the success callback function to update your employee collection and frontend.

    Finally as stated in the comments already. Use something else then user data for your first attempts because user data is mostly very sensitive and needs advanced techniques.

    To complete this here. Your current code will not update the whole page!Your goal is to use the response in a special part of the page without updating the wohle page. This is the concept of AJAX.

    Also be careful with your variable names. This can't work because response is not defined:

    success: function(result) {
        $("#resultadd").html(response);
    }
    

    Just for completion I'm adding code:

    $(document).ready(function() {
        $("#submitbtn").click(function() {
            var first = $("[name='first']").val();
            var last = $("[name='last']").val();
    
            $.ajax({
                type: "POST",
                data: {first: first, last: last},
                url: "https://main.xfiddle.com/51da1682/addEmp1.php",
                success: function(result) {
                    $("#resultadd").html(result);
                }
            });
        });
    });
    
    <?php
        $dummyResponse->first = 'Foo';
        $dummyResponse->last = 'Bar';
    
        if (!$dummyResponse) {
            http_response_code(500);
            echo json_encode(mysqli_error());
        }
    
        http_response_code(200);
        echo json_encode($dummyResponse);
    ?>
    

    This code is working for me, see this fiddle (valid for 2 days). https://main.xfiddle.com/51da1682/addEmpApp4.php

    点赞 评论 复制链接分享

相关推荐