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.
    $

    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 .

    $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.

    //验证是否提交过
    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.

    $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.

    $(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:

    $(".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.

    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 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)

    What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

    Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

    Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

    There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

    Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

    JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

    How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

    How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

    The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

    In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

    How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

    Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

    Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

    Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

    How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

    Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

    See all articles