Home Web Front-end JS Tutorial How does PHP jQuery Ajax Mysql implement the mood expression function_javascript skills

How does PHP jQuery Ajax Mysql implement the mood expression function_javascript skills

May 16, 2016 pm 03:46 PM

The function of posting mood is implemented through php jquery ajax mysql technology. Let me explain the general process first: the homepage index.html page obtains mood icons and histogram related data through ajax. When the user clicks on one of the mood icons, the The background PHP sends a request, PHP verifies the user cookie (whether it is submitted for the first time), and then adds 1 to the corresponding mood field content in the database. After success, it returns to the front-end page, tells the homepage that the index page has been published successfully, and adjusts the histogram and statistical data.

Please see the rendering:

html:

Looking at the HTML first, we place a #msg in index.html to display the operation result information. #mood is the main operation area, where ul loads mood icons, descriptions, histograms and statistical information asynchronously through javascript.

Copy code The code is as follows:






    PHP
    First, we configure the database connection information and example-related parameters in the config.php configuration file.
    $

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    host="localhost";

    $db_user="root";

    $db_pass="";

    $db_name="demo";

    $link=mysql_connect($host,$db_user,$db_pass);

    mysql_select_db($db_name,$link);

    mysql_query("SET names UTF8");

    //心情说明,用半角逗号隔开

    $moodname='震惊,不解,愤怒,杯具,无聊,高兴,支持,超赞';

    //心情图标文件,用半角逗号隔开(template/images/目录)

    $moodpic='a1.gif,a2.gif,a3.gif,a4.gif,a5.gif,a6.gif,a7.gif,a8.gif';

    //统计心情柱图标最大高度

    $moodpicheight=80;

    Copy after login

    Next, we are going to divide mood.php into two parts. By receiving the action parameters, we can divide it into the first part: expressing the mood, and the second part: obtaining mood-related information.

    Copy code The code is as follows:

    include_once("config.php");
    $action = $_GET['action'];
    if($action=='send'){ //Express your mood
    ...
    }else{ //Get mood
    ...
    }

    Part1: Express your mood.
    Users submit mood parameters via post from the front end, including article id and mood id. First verify whether the article exists, then verify whether the user has posted a mood about this article, then operate the database, set the corresponding mood field value to 1, and calculate the height of the histogram corresponding to the current mood, and return it to the front-end js for reception .

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    $id = (int)$_POST['id']; //文章或帖子id

    $mid = (int)$_POST['moodid']; //心情id(配置文件中提供8种心情)

    if(!$mid || !$id){

     echo "此链接不存在";exit;

    }

    $havemood = chk_mood($id); //验证cookie

    if($havemood==1){

     echo "您已经表达过心情了,保持平常心有益身心健康!";exit;

    }

    $field = 'mood'.$mid; //数据表中的心情字段,分别用mood0,mood1,mood2...表示不同的心情字段

    $query = mysql_query("update mood set ".$field."=".$field."+1 where id=".$id); //对应的心情字段值+1

    if($query){

     setcookie("mood".$id, $mid.$id, time()+300); //设置cookie,为了测试我们设置cookie过期时间为300s

     $query2 = mysql_query("select * from mood where id=$id");

     $rs = mysql_fetch_array($query2);//获取该文章的心情数据

     $total = $rs['mood0']+$rs['mood1']+$rs['mood2']+$rs['mood3']+$rs['mood4']+$rs['mood5']+

    $rs['mood6']+$rs['mood7'];

     $height = round(($rs[$field]/$total)*$moodpicheight); //得到总量,并计算当前对应心情的柱状图的高度

     echo $height; //返回当前心情柱状的高度

    }else{

     echo -1; //数据出错

    }

    Copy after login

    To verify whether the user has posted a mood, we use the function chk_mood() to determine whether the user's corresponding cookie exists.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    //验证是否提交过

    function chk_mood($id){

     $cookie = $_COOKIE['mood'.$id];

     if($cookie){

     $doit = 1;

     }else{

     $doit = 0;

     }

     return $doit;

    }

    Copy after login

    Part2: Get mood
    By obtaining the mood data corresponding to the article or post ID in the data table, the value corresponding to each mood is obtained (which can be understood as the number of times the mood is posted), and the height of the histogram is calculated, and the value, name, icon, and The height information is constructed into an array, and finally returned to the front end as JSON format data.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    $mname = explode(',',$moodname);//心情说明

    $num = count($mname);

    $mpic = explode(',',$moodpic);//心情图标

    $id = (int)$_GET['id']; //文章或帖子id

    $query = mysql_query("select * from mood where id=$id"); //查询对应的心情数据

    $rs = mysql_fetch_array($query);

    if($rs){

     //得到发表心情的总量

     $total = $rs['mood0']+$rs['mood1']+$rs['mood2']+$rs['mood3']+$rs['mood4']+

    $rs['mood5']+$rs['mood6']+$rs['mood7'];

     for($i=0;$i<$num;$i++){

     $field = 'mood'.$i; //字段名

     $m_val = intval($rs[$field]); //心情对应的值(次数)

     $height = 0; //柱图高度

     if($total && $m_val){

     $height=round(($m_val/$total)*$moodpicheight); //计算高度

     }

      

     $arr[] = array(

     'mid' => $i, //对应心情id

     'mood_name' => $mname[$i], //心情名称

     'mood_pic' => $mpic[$i], //图标

     'mood_val' => $m_val, //次数

     'height' => $height //柱状图高度

     );

     }

     echo json_encode($arr); //返回JSON数据

    }

    Copy after login

    jQuery

    We use the powerful jQuery to complete all ajax interactive actions in this example, so the jquery.js library must be loaded first in index.html. Currently, version 1.8 has been released. You can go to the official website http: //jquery.com/Download.
    Then we send an Ajax request to mood.php to obtain the mood list information and display it in the index.html page.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    $(function(){

     $.ajax({

     type: 'GET', //通过get方式发送请求

     url: 'mood.php', //目标地址

     cache: false, //不缓存数据,注意文明发表心情的数据是实时的,需将cache设置为false,默认是true

     data: 'id=1', //参数,对应文章或帖子的id,本例中固定为1,实际应用中是获取当前文章或帖子的id

     dataType: 'json', //数据类型为json

     error: function(){

     alert('出错了!');

     },

     success: function(json){ //请求成功后

     if(json){

     $.each(json,function(index,array){ //遍历json数据列

     var str = "<li><span>"+array['mood_val']+"</span><div class="pillar"

    style="height:"+array['height']+"px;"></div><div class="face"

    rel=""+array['mid']+""><img src="images/"+array['mood_pic']+"">

    <br/>"+array['mood_name']+"</div></li>";

      $("#mood ul").append(str); //将数据加入到#mood ul列表中

      });

     }

     }

     });

     ...

    });

    Copy after login

    In this way, after we access index.html, the page will load the mood list. Of course, if you want to see the final arrangement effect, you also need CSS. This article does not explain the relevant CSS. Please download the source code or view the demo to learn more.
    Next, we have an interactive action. When the corresponding mood icon is clicked, the icon is marked as published, the height of the histogram changes, and the number above will change to 1, indicating that the publication is successful. If you continue to click the mood icon, it will prompt that it has been published. Once published, it cannot be resubmitted. Please see the code:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    $(".face").live('click',function(){ //侦听点击事件

     var face = $(this);

     var mid = face.attr("rel"); //对应的心情id

     var value = face.parent().find("span").html();

     var val = parseInt(value)+1; //数字加1

     //提交post请求

     $.post("mood.php&#63;action=send",{moodid:mid,id:1},function(data){

     if(data>0){

     face.prev().css("height",data+"px");

     face.parent().find("span").html(val);

     face.find("img").addClass("selected");

     $("#msg").show().html("操作成功").fadeOut(2000);

     }else{

     $("#msg").show().html(data).fadeOut(2000);

     }

     });

    });

    Copy after login

    If you don’t understand it, you can download the source code and study it carefully. Click the Download button at the beginning of the article to download. Finally, the mysql data table structure required for this example is attached. Thank you for your attention.

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    CREATE TABLE IF NOT EXISTS `mood` (

     `id` int(11) NOT NULL,

     `mood0` int(11) NOT NULL DEFAULT '0',

     `mood1` int(11) NOT NULL DEFAULT '0',

     `mood2` int(11) NOT NULL DEFAULT '0',

     `mood3` int(11) NOT NULL DEFAULT '0',

     `mood4` int(11) NOT NULL DEFAULT '0',

     `mood5` int(11) NOT NULL DEFAULT '0',

     `mood6` int(11) NOT NULL DEFAULT '0',

     `mood7` int(11) NOT NULL DEFAULT '0',

     PRIMARY KEY (`id`)

    ) ENGINE=MyISAM DEFAULT CHARSET=utf8;

    INSERT INTO `mood` (`id`, `mood0`, `mood1`, `mood2`, `mood3`, `mood4`, `mood5`, `mood6`, `mood7`)

    VALUES(1, 8, 6, 20, 16, 6, 9, 15, 21);

    Copy after login

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Article

    Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Nordhold: Fusion System, Explained
    4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
    3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Hot Topics

    Java Tutorial
    1674
    14
    PHP Tutorial
    1278
    29
    C# Tutorial
    1257
    24
    Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

    Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

    JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

    The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

    JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

    JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

    Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

    Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

    Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

    Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

    Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

    Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

    The Role of C/C   in JavaScript Interpreters and Compilers The Role of C/C in JavaScript Interpreters and Compilers Apr 20, 2025 am 12:01 AM

    C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

    Python vs. JavaScript: Use Cases and Applications Compared Python vs. JavaScript: Use Cases and Applications Compared Apr 21, 2025 am 12:01 AM

    Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

    See all articles