Home  >  Article  >  Backend Development  >  Ajax asynchronous submission for PHP7 message board development

Ajax asynchronous submission for PHP7 message board development

coldplay.xixi
coldplay.xixiforward
2020-12-18 09:10:461730browse
PHP7 TutorialIntroducing Ajax asynchronous submission about message board development

Ajax asynchronous submission for PHP7 message board development

##Recommended (free):

php7 Tutorial,ajax tutorial

Preface
This tutorial is the most important part of this album. With the continuous iterative updates of front-end technology, the implementation of many functions of the website has been transferred to the front-end. Judging from the programming language rankings in the first quarter of 2018, JavaScript is still the most popular programming language. So if you want to learn js in depth, Ajax is essential.

I have talked about js verification in the previous course. The courseware code is modified based on the PHP7 message board development (JS verification) of Friends. It can be easily completed by just adding the ajax asynchronous operation part.

It should be noted that here we will not explain in detail what the XMLHttpRequest object is, why we should use it, etc. I believe that if you can use it again, you will be more impressed if you learn more about it. I will try my best here. Less text-based test-oriented teaching can achieve learning results.

Open the editor and get started!

Explanation of the core part of Ajax asynchronous
// 第一步 创建 XMLHttpRequest 对象,为了更容易理解,变量就用ajax
var ajax = new XMLHttpRequest();

// 第二步 初始化一个Ajax请求,url参数是远程请求地址ajax.php
ajax.open('POST', url, true); // 这里用到post提交留言,所以用post方式提交给服务器
// ajax.open('GET', url, true); // get方式请求服务器

// 第三步 发送请求;如果该请求是异步模式(默认),该方法会立刻返回。
ajax.send(inputdata);

// 第四步 发送请求总该要知道有没收到吧,这里就需要用到Ajax的事件监听器onreadystatechange 
ajax.onreadystatechange = function(){
    // 这里判断服务器是否有数据响应,如果有则做些你要处理的逻辑,比如提示用户操作成功
}
If you still can’t understand the above four steps, you can think of it as the first step to find a friend A to send an email, and the second step to send an email to this A The friend wrote the content of the letter and encapsulated it with the address and affixed a stamp. The third step was to deliver the mail. After a while (of course there was an immediate response if the Internet connection was available), the fourth step was to receive a reply from friend A. I was very happy. Next, you can do things based on the content of the reply, such as meeting (online) or making an appointment...

Okay, that’s it. Here is the complete code.

HTML JS page code
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>留言板_科科分享</title>
        <!-- 2.新建css样式文件并根据效果图编写css代码 -->
        <link rel="stylesheet" href="feedback.css">
        <!-- 3.js表单验证 -->
        <script type="text/javascript">
            function checkform(){
                var nickname = document.getElementsByTagName('input')[0].value; // 获取用户输入的姓名
                var tel = document.getElementsByTagName('input')[1].value; // 获取用户输入的联系方式
                var content = document.getElementsByTagName('textarea')[0].value; // 获取用户输入的留言内容
                // 如果没有输入姓名 则提示
                if(nickname == ''){
                    alert('请输入您的姓名');
                    document.getElementsByTagName('input')[0].focus(); // 将光标定位到姓名输入框
                    return false; // 阻止冒泡 输入姓名后才能通过
                }
                // 如果没有输入联系方式 则提示
                if(tel == ''){
                    alert('请输入您的联系方式');
                    document.getElementsByTagName('input')[1].focus(); // 将光标定位到联系方式输入框
                    return false;  // 阻止冒泡 输入联系方式才能通过
                }
                // 如果没有输入留言内容 则提示
                if(content == ''){
                    alert('请输入您的联系方式');
                    document.getElementsByTagName('textarea')[0].focus(); // 将光标定位到留言内容输入框
                    return false;  // 阻止冒泡 输入留言内容才能通过
                }
                
                // js已经拿到了用户提交的数据,那接下来就是AJAX(页面无刷新提交数据到服务器-异步通信)
                // 异步请求 start
                var ajax, url, inputdata;
                // 创建 XMLHttpRequest 对象
                if(window.XMLHttpRequest){
                    ajax = new XMLHttpRequest();
                }else{
                    // 兼容Internet Explorer(IE5 和 IE6)使用 ActiveX 对象
                    ajax = new ActiveXObject("Microsoft.XMLHTTP");
                }
                url = 'ajax.php';
                ajax.open('POST', url, true);
                ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");  // 用POST的时候一定要有这句
                inputdata = 'nickname='+nickname+'&tel='+tel+'&content='+content;
                ajax.send(inputdata);
                // 接收服务器返回的数据
                ajax.onreadystatechange = function(){
                    // 获取服务器响应状态码
                    if(ajax.readyState == 4 && ajax.status==200){
                        // 获取服务器返回的响应返回的数据
                        var retdata = ajax.responseText;
                        if(retdata == 1){
                            alert('留言信息已提交成功!感谢您的宝贵意见。');
                        }
                    }
                }
                // 异步请求 end
                return false; // 这里是为了方式submit点击后表单自动提交
                // document.feedback_form.submit(); // 提交用户数据到后端action中的地址
            }
        </script>
    </head>
    <body>
        <!-- 工作区,呈现给用户看的 -->
        <!-- 1.开始搭建脚手架 -->
        <p class="container_box">
            <p class="up">
                <h3 class="title">留言板</h3>
                <h5 class="subtitle">FEEDBACK</h5>
            </p>
            <p class="down">
                <form name="feedback_form" action="/#" method="post" onsubmit="return false;">
                    <p class="input">
                        <input type="text" class="fl" name="name" placeholder="输入您的姓名" /> 
                        <input type="text" class="fr" name="tel" placeholder="输入您的联系方式" />
                    </p>
                    <textarea class="content" cols="30" rows="10" name="nr"></textarea>
                    <input type="submit" onclick="checkform()" value="提交您的留言" class="sub" />
                </form>
            </p>
        </p>
    </body>
</html>
PHP code (ajax.php)
<?php
include &#39;config.php&#39;;

// POST接收用户提交的数据
$nickname = !empty($_POST[&#39;nickname&#39;])? addslashes(strip_tags($_POST[&#39;nickname&#39;])):&#39;&#39;; // 留言人名称
$tel = !empty($_POST[&#39;tel&#39;])?addslashes(strip_tags($_POST[&#39;tel&#39;])):&#39;&#39;; // 留言人的联系方式
$content = !empty($_POST[&#39;content&#39;])?addslashes(strip_tags($_POST[&#39;content&#39;])):&#39;&#39;; // 留言内容
$time = time(); // 当前系统时间,即用户留言时间

// 插入mysql语句
$sql = "INSERT INTO feedback (name, contact, content, addtime) VALUES (&#39;{$nickname}&#39;, &#39;{$tel}&#39;, &#39;{$content}&#39;, &#39;{$time}&#39;)";

// 立即执行mysql语句
$result = mysqli_query($mysqli, $sql); // 返回一个资源标识符,通常是数字
$insert_id = mysqli_insert_id($mysqli); // 返回数据表的自增长ID,比如新用户注册返回用户ID
// echo $insert_id; // 当你在调试的时候,你会发现echo是很好的帮手。
if($insert_id > 0){
    // 如果入库成功,这里可以处理其他想要的逻辑
    echo 1;
    exit;  // 退出程序,使其不再往下执行代码
}
// 这是错误的时候返回0
echo 0;
exit;
Remember to practice! Welcome to doodle in the comment area below! ~

The above is the detailed content of Ajax asynchronous submission for PHP7 message board development. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jianshu.com. If there is any infringement, please contact admin@php.cn delete