Php+jquery+ajax+mysql realizes the function of expressing mood

Source: Internet
Author: User
Tags array exit config explode html page json mysql query

We browse the website article or post, we need to express their feelings after browsing, in many sites have provided to the user to express the mood of the function, through this function can be intuitive statistical analysis of the article or post browser mood feeling data. In this article, you will learn how to implement a mood icon by clicking on it instantly.

Download http://bbs.php100.com/read-htm-tid-391083-ds-1.html

This article through an example to explain the use of php+jquery+ajax+mysql combined to achieve the user to express the mood of the function, simple operation, practical, is a comprehensive application of web knowledge of the article, so readers need to have PHP, Mysql, jquery and Ajax-related knowledge.

The general principle and process for this example is this: Main Page index.html through Ajax to get mood icon and histogram related data, when the user clicks on one of the mood icon, to the back of PHP to send a request, PHP authentication user cookie To prevent repeated submissions, and then the corresponding data in the MySQL content of the mood field add 1, into After work returns the front page, tells Index.html to publish successfully, and adjusts the histogram and statistics.

Html

First look at the HTML, we put a #msg in the index.html, used to display the results of the operation of information, #mood是操作主区域, where the UL through JavaScript asynchronous load mood icon, description, histogram and statistics information.

 
<div id="msg"></div> 
    <div id=mood> 
    <ul></ul> 
</div> 

Php

First, in the config.php configuration file, we configure the database connection information, as well as sample related parameters.

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

Next, we are in the mood.php in two parts, by receiving the action parameters, divided into the first part: The mood, the second part: Get the mood related information.

 
include_once("config.php"); 
 
$action = $_GET['action']; 
if($action=='send'){ //发表心情 
    ... 
}else{ //获取心情 
    ... 
} 

Part1: Express mood.

The user submits a post-mood parameter from the front end, including the article ID, the mood ID. First verify the existence of the article, and then verify that the user has been published in the mood of this article, and then operate the database, the corresponding mood of the field value of +1, and calculate the current mood corresponding to the height of the histogram, return to the front-end JS receive.

  $id  =  (int) $_post[' id ']; //article or post id  $mid  =  (int) $_post[' Moodid ']; // Mood ID (8 moods in configuration file)   if (! $mid   ! $id) {      echo  "This link does not exist";exit; }     $havemood  = chk_mood ($id);  //validation cookie  if ($havemood ==1) {       echo  "You have expressed the mood, to keep the normal heart healthy and healthy!" ";exit; }  $field  =  ' mood '. $mid;  //the mood fields in the datasheet, respectively, with mood0,mood1,mood2 ... Represents a different mood field   $query  = mysql_query ("update mood set ". $field. " = ". $field." +1 where id= ". $id);  //corresponding mood field value +1  if ($query) {      setcookie (" Mood " . $id,  $mid. $id,  time () +300);  //set cookies to test that we set the cookie expiration to 300s      $ Query2 = mysql_query ("select * from mood where id= $id");        $rs  = mysql_fetch_array ($query 2);//Get the mood data for the article   &NBSP;&NBSP;&NBSP;&NBSP; $total  =  $rs [' mood0 ']+ $rs [' mood1 ']+ $rs [' mood2 ']+ $rs [' mood3 ']+ $rs [' mood4 ']+ '] $rs [' The ' '] [' mood5 ']+  $rs ['] Mood6 ']+ $rs [' Mood7 '];       $height  = round ($rs [$field]/$total] *$ Moodpicheight);  //gets the total amount and calculates the height       echo  $height of the current histogram of the corresponding mood;  //
 Returns the height of the current mood column  }else{      echo -1; //data error  } 

Verify that the user has been published, 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; 
} 

Part2: Get the mood

by getting the mood data for the article or post ID in the datasheet, get each mood corresponding to the value (can be understood as the number of mood), and calculate its histogram height, each mood corresponding to the value, name, icon, height information structure caused by the array, and finally in JSON format data returned to the front-end.

  $mname  = explode (', ', $moodname);/Mood description   $num  = count ($mname);  $mpic  =  explode (', ', $moodpic);/mood icon     $id  =  (int) $_get[' id ']; //article or post id  $query  = mysql_query ("select * from mood where id= $id")  //query corresponding mood data   $ Rs = mysql_fetch_array ($query);  if ($rs) {      //get the total amount of mood published         $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;  //field name             $m _val = intval ($rs [$field])  //mood values (times)             $height  = 0; //Column chart height            if($total  &&  $m _val) {               $height =round ($m _val/$total) *$ moodpicheight);  //Computing height           }                         $ Arr[] = array (               ' mid '  =>  $i,  //corresponding mood id                ' Mood_name '  =>  $mname [$i], //mood name                 ' mood_pic '  =>  $mpic [$i], //icon                 ' Mood_val '  =>  $m _val, //times                 ' height '  =>  $height  //column height           );      }   
    echo json_encode ($arr);  //returns JSON data  } 

Jquery

We use powerful jquery to complete this example of all Ajax interaction, so in the index.html to load the Jquery.js library, the current version of 1.8 has been released Oh, can go to the official website http://jquery.com/download.

Then we send the AJAX request to mood.php, get the Mood list information and display it in the Index.html page.

  $ (function () {      $.ajax ({           type:  ' Get ',  //send request by get way           url:  ' Mood.php ',  //destination address           cache: false, //do not cache data, Note that the civilized mood of the data is real-time, you need to set the cache to False, the default is true          data:  ' id=1 ' ,  //parameters, the ID of the corresponding article or post, in this case, fixed to 1, the actual application is to get the current article or post id           datatype:  ' JSON ',  //data type json          error:  function () {              alert (' Wrong! ');          },           success: function (JSON) { //after successful request                if (JSON) {  &Nbsp;               $.each (JSON, function (Index,array) { //traversal JSON data columns                        var str =  "<li><span>" + array[' Mood_val ']+ "</span><div class=\" pillar\ "   style=\" Height: "+array[' height ']+ ' px ; \ "></div><div class=\" face\ "   rel=\" "+array[' mid ']+" \ ">  <br/>" +array[' mood_name ']+ "</div></li>";                        $ ("#mood  ul"). Append (str);  //add data to #mood ul list          &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP});                }          }    
 &NBSP;&NBSP});      ... }); 

In this way, we visit the index.html, the page will be loaded into the mood list, of course, to see the final arrangement effect, but also need CSS, this article does not explain the relevant CSS, please download the source code or view demo to understand.

Next, we have an interactive action, when clicked on the corresponding mood icon, the icon is identified as published, the histogram height changes, and the number above will be +1, indicating success, if you continue to click the mood icon, will be prompted has been published can not be repeated submissions. Please look at the code:

  $ (". Face"). Live (' click ', Function () { //Listening click event       var face =
 $ (This);      var mid = face.attr ("rel")  //corresponding mood id      var value = face.parent (). FIND ("span"). HTML ();     
 var val = parseint (value) +1; //number plus 1      //submit POST request       $.post ("Mood.php?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 ("Operation succeeded"). Fadeout;           }else{              $ ("#msg"). Show (). HTML (data). fadeout;          }      
 }); }); 

No See the children's shoes can download the source carefully study, click the beginning of the article download button to download, finally attached to this example of the MySQL data table structure, thank you for your concern.

  create table if not exists  ' mood '   (     ' id '  int (11)
 NOT NULL,     ' mood0 '  int (one)  NOT NULL DEFAULT  ' 0 ',     ' mood1 '  int  NOT NULL DEFAULT  ' 0 ',     ' mood2 '  int (  NOT NULL DEFAULT  ' 0 ',     ' mood3 '  int (one)  NOT NULL  default  ' 0 ',     ' mood4 '  int (one)  NOT NULL DEFAULT  ' 0 ',      ' Mood5 '  int (one)  NOT NULL DEFAULT  ' 0 ',     ' Mood6 '  int (11)  NOT NULL DEFAULT  ' 0 ',     ' Mood7 '  int (one)  NOT NULL  default  ' 0 ',    PRIMARY KEY  (' id ')  )  ENGINE=MyISAM DEFAULT  charset=utf8;      insert into  ' mood '   (' id ',  ' mood0 ',  ', ' mood1 ',  ') Mood2 ',  ' mood3 ', &nbsp. ' mood4 ',  ' mood5 ',  ' mood6 ',  ' mood7 ')   VALUES (1, 8, 6, 20, 16,  6,&NBSP;9,&NBSP;15,&NBSP;21); 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.