PHP + jQuery + Ajax + Mysql enables mood posting

Source: Internet
Author: User
After browsing a website article or post, we need to express our feelings after browsing. many websites provide users with the ability to express their feelings, this function allows you to visually analyze the mood data of the viewer of an article or post. In this article, you will learn how to implement...

After browsing a website article or post, we need to express our feelings after browsing. many websites provide users with the ability to express their feelings, this function allows you to visually analyze the mood data of the viewer of an article or post. In this article, you will learn how to instantly express your mood by clicking the mood icon.

 

This article uses examples to explain how to use PHP + jQuery + Ajax + Mysql to achieve the user's mood posting function, which is simple and practical, is an article that comprehensively applies WEB knowledge. Therefore, you must have knowledge about PHP, Mysql, jQuery, and ajax.

The general principle and process of this example are as follows: the histogram is successfully published, and the bar chart and statistical data are adjusted.

HTML

First, in HTML, we place a # msg in index.html to display the operation result. # mood is the main region of the operation. ul asynchronously loads the mood icon, description, bar chart, and statistical information through javascript.

           
 
 
      
    PHP

    First, configure the database connection information and 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"); // mood description, separated by commas $ moodname = ', shocked, puzzled, angry, CUP, bored, happy, supported, awesome '; // mood icon files separated by commas (template/images/directory '; // calculate the maximum height of the Mood Bar Icon $ moodpicheight = 80;

    Next, we will prepare two parts in mood. php. by receiving the action parameter, we will divide it into the first part: posting mood, and the second part: getting mood-related information.

    Include_once ("config. php "); $ action = $ _ GET ['action']; if ($ action = 'send') {// express mood ...} else {// Get mood ...}

    Part1: express your mood.

    The user submits the mood parameters from the front end through post, including the article id and mood id. First, verify the existence of the article, and then verify whether the user has been in a mood for this article. then, operate the database php100.com and add the corresponding mood field value to 1, calculate the height of the bar chart corresponding to the current mood and return it to the front-end js for receiving.

    $ Id = (int) $ _ POST ['id']; // article or POST id $ mid = (int) $ _ POST ['moodid']; // mood id (eight moods are provided in the configuration file) if (! $ Mid |! $ Id) {echo "This link does not exist"; exit;} $ havemood = chk_mood ($ id); // verify the cookie if ($ havemood = 1) {echo "you have already expressed your mood. it is helpful to maintain a normal mind! "; Exit;} $ field = 'mood '. $ mid; // mood fields in the data table, using mood0, mood1, mood2... it indicates different mood fields $ 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); // sets the cookie, in order to test the setting of cookie expiration time to 300 s $ query2 = mysql_query ("select * from mood where id = $ id"); $ rs = mysql_fetch_array ($ query2 ); // Obtain the mood data of this article $ total = $ rs ['mood0'] + $ rs ['moo1'] + $ rs ['mood2'] + $ rs ['mood3 '] + $ rs ['mood4'] + $ rs ['mood5'] + $ rs ['mood6'] + $ rs ['mood7']; $ height = round ($ rs [$ field]/$ total) * $ moodpicheight); // obtain the total amount and calculate the height of the bar chart corresponding to the current mood echo $ height; // return the height of the column in the current mood} else {echo-1; // data error}

    Verify whether the user has expressed his or her mood. the chk_mood () function is used to determine whether the user's cookie exists.

    // Verify whether the function chk_mood ($ id) {$ cookie =$ _ COOKIE ['mood '. $ id]; if ($ cookie) {$ doit = 1;} else {$ doit = 0;} return $ doit ;}

    Part2: Get mood

    Obtain the mood data corresponding to the document or post id in the data table, obtain the value of each mood (which can be understood as the number of times the mood is posted), and calculate the height of the column chart, construct the values, names, icons, and heights of each mood into an array and return the data in JSON format 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 the corresponding mood data $ rs = mysql_fetch_array ($ query ); if ($ rs) {// get the total number of posted moods $ total = $ rs ['mood0'] + $ rs ['moo1'] + $ 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]); // The value of mood (times) $ height = 0; // bar chart height if ($ total & $ m_val) {$ height = round ($ m_val/$ total) * $ moodpicheight ); // calculation height} $ arr [] = array ('mid '=> $ I, // mood id 'od _ name' => $ mname [$ I], // mood name 'od _ pic '=> $ mpic [$ I], // Icon 'od _ VAL' => $ m_val, // times 'height' => $ height // bar chart height);} echo json_encode ($ arr); // return JSON data}
    JQuery

    We use a strong jqueryto complete all the ajax‑based templates in the cost example. For this reason, we need to first load the jquery. js library in index.html. Currently, version 1.8 has been released. you can download it at http://jquery.com/on the official website.

    Send an ajaxrequest to mood.php, receive the information, and display it on the index.html page.

    $ (Function () {$. ajax ({type: 'GET', // send the request url in the GET method: 'Mood. php ', // target address cache: false, // no data is cached. Note that the data in the mood of a civilized expression is real-time. set the cache to false. the default value is true data: 'id = 1', // parameter, corresponding to the article or post id, which is set to 1 in this example. in actual application, it is to obtain the id dataType of the current article or post: 'json ', // the data type is json error: function () {alert ('error! ');}, Success: function (json) {// if (json) {$. each (json, function (index, array) {// traverses the json data column var str ="
  • "+ Array ['od _ VAL'] +"
    "+ Array ['mood _ name'] +"
  • "; $ (" # Mood ul "). append (str); // add data to # mood ul List });}}});...});

    In this case, after index.html is uploaded, the page will load the mood list. of course, to see the final arrangement effect, CSS is also required. This article does not explain the relevant CSS. please download the source code or view the demo for details.

    Next, we have an interactive action. when you click the corresponding mood icon, the icon is marked as published, the height of the bar chart changes, and the number above will be + 1, indicating that the posting is successful, if you continue to click the mood icon, you will be prompted that you have published a post and cannot submit it again. See the code:

    $ (". Face "). live ('click', function () {// listener click event var face =$ (this); var mid = face. attr ("rel"); // The mood id var value = face. parent (). find ("span" ).html (); var val = parseInt (value) + 1; // add 1 to the number // submit the 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" pai.html (val); face. find ("img "). addClass ("selected"); $ ("# msg" ).show().html ("Operation successful "). fadeOut (2000);} else {$ ("# msg" ).show().html (data ). fadeOut (2000 );}});});

    If you do not understand the source code, you can Download the source code. click the Download button at the beginning of the article to Download it. the mysql data table structure required in 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); 
      
    

    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.