Php+jquery+ajax+mysql How to realize the _javascript skill of expressing mood function

Source: Internet
Author: User
Tags explode

The realization of the post mood function through Php+jquery+ajax+mysql technology, The general process I first give you a reason: Home index.html page 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 to the user cookie verification (whether it is the first submission), and then the database corresponding mood field content plus 1, after the successful return Front page, tell home index page to publish successfully, and adjust histogram and statistic data.

Please see the effect chart:

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.

Copy Code code as follows:

<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");
Mood description, separated by a half-width comma
$moodname = ' shocked, puzzled, angry, cup, boring, happy, support, Super praise ';
Mood icon file, separated by Half-width commas (template/images/directory)
$moodpic = ' a1.gif,a2.gif,a3.gif,a4.gif,a5.gif,a6.gif,a7.gif,a8.gif ';
Statistics mood column icon Maximum height
$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.

Copy Code code as follows:

Include_once ("config.php");
$action = $_get[' action '];
if ($action = = ' send ') {//Express mood
...
}else{//Get the mood
...
}

Part1: Publish the 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); Verify that the cookie
if ($havemood ==1) {
 echo] You have expressed your feelings, and keep your mind healthy! "; exit;
}
$field = ' mood '. $mid; The mood field 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); The corresponding mood field value +1
if ($query) {
 Setcookie ("Mood". $id, $mid. $id, Time () +300);//Set Cookies, To test we set the cookie expiration time to 300s
 $query 2 = mysql_query ("Select * from mood where id= $id");
 $rs = Mysql_fetch_array ($query 2);//Get the mood data for the article
 $total = $rs [' mood0 ']+ $rs [' mood1 ']+ $rs [' mood2 ']+ $rs [' mood3 ']+$] rs[' mood4 ']+ $rs [' mood5 ']+
$rs [' Mood6 ']+ $rs [' Mood7 '];
 $height = Round (($rs [$field]/$total) * $moodpicheight); Get the total amount, and compute the height echo $height of the histogram of the current mood;//Return to the
 current mood columnar height
}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.

Verify that the
function Chk_mood ($id) {
 $cookie = $_cookie[' mood '. $id] is submitted;
 if ($cookie) {
 $doit = 1;
 } else{
 $doit = 0;
 }
 return $doit;
}

Part2: Get the mood
By getting the mood data that corresponds to 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 W" Here id= $id "); Query the corresponding mood data
$rs = mysql_fetch_array ($query);
if ($rs) {
 //Get the total amount of the published mood
 $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 corresponding value (times)
 $ Height = 0; Column Chart Height
 if ($total && $m _val) {
 $height =round ($m _val/$total) * $moodpicheight);//Compute height
 }
 
 $arr [] = Array (
 ' mid ' => $i,//corresponds to the mood ID
 ' mood_name ' => $mname [$i],//Mood name
 ' mood_pic ' => $mpic [$i], Icon
 ' mood_val ' => $m _val,//Times
 ' height ' => $height//histogram height
 );
 }
 echo Json_encode ($arr); Return 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 URL via get
 : ' 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 ',//parameter, the corresponding article or post ID, in this case fixed to 1, the actual application is to get the current article or post ID
 DataType: ' json ',//data type is JSON
 error:function () {
 alert (' Error! ');
 },
 success:function (JSON) {//Request successful
 if (JSON) {
 $.each (json,function (Index,array) {// Traversal JSON data column
 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 the #mood UL list
  };}}
 );
 ...
});

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"); The 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 ();}
 });


Do not see the children's shoes can download the source carefully study, click the beginning of the article download button can be downloaded, and finally attached to this example of the MySQL data table structure, thank you for your concern.

CREATE TABLE IF not EXISTS ' mood ' (
 ' id ' int (one) not null,
 ' mood0 ' int (one) not null DEFAULT ' 0 ',
 ' mood1 ' int (1 1) NOT null default ' 0 ',
 ' mood2 ' int (one) not null default ' 0 ',
 ' mood3 ' int (one) not null default ' 0 ',
 ' mood4 ' I NT (one) NOT null default ' 0 ',
 ' mood5 ' int (one) not null default ' 0 ',
 ' mood6 ' int (one) not null default ' 0 ',
 ' mood 7 ' int (one) 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);

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.