dqc3469 2017-03-23 08:57
浏览 32
已采纳

如何在不重新加载页面的情况下更新和输出数据库

I have data which is a name. And I am having an input type=text where the value is equals to the name, together with a button type=submit. So what i'm trying to do is that, i want to change and update the name in my database and also output the new name without reloading the page at once because I want to run a JS function (Not Alert but a Toast Notification) which is I cannot do. So to shorten, ( EDIT -> UPDATE -> SHOW = without reloading the page).

EDIT:: I'm sorry I forgot to mention. I know jQuery and AJAX is the solution but I am having trouble understanding AJAX not unlike jQuery.

profile.php (FORM CODE)

<form action="profile.php" method="POST">    
      <input type="text" id="changename" name="changename" class="form-control" placeholder="New Name" required>
      <button id="btnchange" type="submit"></button>
</form>

profile.php (PHP CODE)

    <?php
    if(isset($_POST['changename'])) {
        require 'connect.php';

        $newname = $_POST['changename'];
        $user_id = $_SESSION['temp_user'];

        $sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'";
        if(mysqli_query($conn, $sql)){
            header('location: profile.php');
            // MY JS FUNCTION HERE //
        }

        mysqli_close($conn);
    }
?>
  • 写回答

2条回答 默认 最新

  • dongqiaolong9034 2017-03-23 09:46
    关注

    How to update and output a databse without reloading the page? what u looking for is AJAX. I know you have selected the answer, but there's an extra information that you need that might help you in the long run

    The are some good ajax tutorials you can follow in the web

    1. Ajax Introduction
    2. What is Ajax ?

    And many more you can find on the web.

    This is what u need to do, first your form method is GET and on your php script you are requesting an $_POST therefore this will generate an undifined notice error,changename : notice : undifined variable changename so the solution is to use one method in a single form if your form is $_GET you use $variable = $_GET['fieldname'] if form method is POST on your server side use $variable = $_POST['fieldname']; not the way you did. So lets change your form method to POST Then this is what u should do.

    edit.php

    Update

    <script type="text/javascript">
        $('document').ready(function(){
    
            $('form').on('submit',function(event){
    
                event.preventDefault();//prevent the form from reloading the page when submit
    
                var formData = $('form').serialize(); // reading form input
    
                $.ajax({
    
                    type :'POST',
                    data : formData,
                    url  : 'profile.php', 
                    dataType : 'json',
                    encode : true,
                    success : function(response){
    
                        //response = JSON.parse(response);
    
                        if(response == "ok"){
                            $('#success').html('profile updated success');
                             setTimeout(' window.location.href = "profile.php"; ', 6000); // redirecting
                        }else{
                            //could not update
    
                            $('#error').html(response);
    
                        }
                    },
                    error : function(e){
    
                        console.log(e); // debugging puporse only
                    }
    
                });
            });
        });
    </script>
    

    That's what you need on the frontend side.. Please note if you have more than one form in a single page then do not use $('form').on('submit',function(event){}); you then give each form a unique ID then on replace the form on jquery/ajax with the iD of the form u wanna submit.

    Then your server side.

    I have noticed that you have header('location: profile.php'); that's for redirecting, since we are sending ajax request to the server and back to the client, you don't redirect on the server side, your redirect using the client side after you have received the response you expected from the server. I have commented that section where I do redirecting with client side, on the script above.

    profile.php

    <?php
    
            $message = '';
        if(isset($_POST['submit'])) {
            require 'connect.php';
    
            //validate your input field
            $newname = $_POST['changename'];
            $user_id = $_SESSION['temp_user'];
    
            $sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'";
            if(mysqli_query($conn, $sql)){
    
               $message = 'ok'; // success
            }else{
    
                $message = 'system error could not update please try again later';
            }
    
            echo json_encode($message);//sending response back to the client
    
            mysqli_close($conn);
        }
    ?>
    

    That's all you need, note you need to validate all your inputs fields in both the client and server side before using them.

    I would also advice you to learn more about prepared statements, using mysqli or PDO they are very easy to use and very safe.

    running a query like this : $sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'"; is very unsafe, your inputs are not validated and not filtered and sanitized.

    so with prepared statements its easy like :

    profile.php prepared

     <?php
    
            $message = '';
        if(isset($_POST['submit'])) {
            require 'connect.php';
    
            //validate your input field
            $newname = $_POST['changename'];
            $user_id = $_SESSION['temp_user'];
    
    
            //prepare and bind
            $sql = $conn->prepare("UPDATE login SET login_name= ?  WHERE user_id= ? ");
            $sql->bind_param("si",$newname,$user_id);
    
            if($sql->execute()){
    
                $message = 'ok';
            }else{
    
                $message = 'Error Could not update please try again later';
            }
    
            echo json_encode($message);
    
            $conn->close();
    
    
    
        }
    ?>
    

    $sql->bind_param("si",$newname,$user_id); This function binds the parameters to the SQL query and tells the database what the parameters. are.By telling mysql what type of data to expect, we minimize the risk of SQL injections.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作