0

Here is my index.php:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Voting Page</title>
<script type="text/javascript" src="js/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {

    //####### on page load, retrive votes for each content
    $.each( $('.voting_wrapper'), function(){

        //retrive unique id from this voting_wrapper element
        var unique_id = $(this).attr("id");

        //prepare post content
        post_data = {'unique_id':unique_id, 'vote':'fetch'};

        //send our data to "vote_process.php" using jQuery $.post()
        $.post('vote_process.php', post_data,  function(response) {

                //retrive votes from server, replace each vote count text
                $('#'+unique_id+' .up_votes').text(response.vote_up +' user has voted'); 
            },'json');
    });



    //####### on button click, get user vote and send it to vote_process.php using jQuery $.post().
    $(".voting_wrapper .voting_btn").click(function (e) {

        //get class name (down_button / up_button) of clicked element
        var clicked_button = $(this).children().attr('class');

        //get unique ID from voted parent element
        var unique_id   = $(this).parent().attr("id"); 


        if(clicked_button==='up_button') //user liked the content
        {
            //prepare post content
            post_data = {'unique_id':unique_id, 'vote':'up'};

            //send our data to "vote_process.php" using jQuery $.post()
            $.post('vote_process.php', post_data, function(data) {

                //replace vote up count text with new values

                $('#'+unique_id+' .up_votes').text(data);
                //thank user for liking the content
dataModified = data+' users has voting including you';
$('#message-status').hide().html(dataModified).fadeIn('slow').delay(5000).hide(1);
            }).fail(function(err) { 

            //alert user about the HTTP server error
            alert(err.statusText); 
            });
        }

    });
    //end 

});

</script>
<style type="text/css">
<!--
.content_wrapper{width:500px;margin-right:auto;margin-left:auto;}
h3{color: #979797;border-bottom: 1px dotted #DDD;font-family: "Trebuchet MS";}

/*voting style */
.voting_wrapper {display:inline-block;margin-left: 20px;}
.voting_wrapper .up_button {background: url(images/index.png) no-repeat;float: left;width: 50px;cursor:pointer;}
.voting_wrapper .up_button:hover{background: url(images/index.png) no-repeat;}
.voting_btn{float:left;margin-right:5px;}
.voting_btn span{font-size: 11px;float: left;margin-left: 3px;}

-->
</style>
</head>

<body>
<div class="content_wrapper">
    <h3><img src="9780143332497.jpg" alt=""><br />

        <!-- voting markup -->
        <div class="voting_wrapper" id="1001">
            <div class="voting_btn">
                <div class="up_button">&nbsp;</div><span class="up_votes"></span>
            </div>
        </div>
        <!-- voting markup end -->
    </h3>
<span id="message-status"></span>
</div>
</body></html>

and vote_process.php:

<?php
    ####### db config ##########
    $db_username = 'root';
    $db_password = '';
    $db_name = 'voter';
    $db_host = 'localhost';
    ####### db config end ##########

if($_POST)
{

    ### connect to mySql
    $sql_con = mysqli_connect($db_host, $db_username, $db_password,$db_name)or die('could not connect to database');

    //get type of vote from client
    $user_vote_type = trim($_POST["vote"]);

    //get unique content ID and sanitize it (cos we never know).
    $unique_content_id = filter_var(trim($_POST["unique_id"]),FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_LOW | FILTER_FLAG_STRIP_HIGH);

    //Convert content ID to MD5 hash (optional)
    $unique_content_id = hash('md5', $unique_content_id);

    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        die();
    } 


    switch ($user_vote_type)
    {           

        ##### User liked the content #########
        case 'up': 

            //check if user has already voted, determined by unique content cookie
            if (isset($_COOKIE["voted_".$unique_content_id]))
            {
                header('HTTP/1.1 500 User Already Voted'); //cookie found, user has already voted
                exit(); //exit script
            }

            //get vote_up value from db using unique_content_id
            $result = mysqli_query($sql_con,"SELECT vote_up FROM voting_count WHERE unique_content_id='$unique_content_id' LIMIT 1");
            $get_total_rows = mysqli_fetch_assoc($result);

            if($get_total_rows)
            {
                //found record, update vote_up the value
                mysqli_query($sql_con,"UPDATE voting_count SET vote_up=vote_up+1 WHERE unique_content_id='$unique_content_id'");
            }else{
                //no record found, insert new record in db
                mysqli_query($sql_con,"INSERT INTO voting_count (unique_content_id, vote_up) value('$unique_content_id',1)");
            }

            setcookie("voted_".$unique_content_id, 1, time()+7200); // set cookie that expires in 2 hour "time()+7200".
            echo ($get_total_rows["vote_up"]+1); //display total liked votes
            break;  

        ##### respond votes for each content #########      
        case 'fetch':
            //get vote_up and vote_down value from db using unique_content_id
            $result = mysqli_query($sql_con,"SELECT vote_up,vote_down FROM voting_count WHERE unique_content_id='$unique_content_id' LIMIT 1");
            $row = mysqli_fetch_assoc($result);

            //making sure value is not empty.
            $vote_up    = ($row["vote_up"])?$row["vote_up"]:0; 

            //build array for php json
            $send_response = array('vote_up'=>$vote_up, 'vote_down'=>$vote_down);
        echo json_encode($send_response);
            break;

    }

}
?>

And here is my html existing worked jsfiddle: http://jsfiddle.net/grkzcc5u/

I have been created vote system in php[index.php and vote_process.php], so

I need to add above two php files into my index html file.

For me this is the new think, I m blank about this one.

can anyone help me to fix this,?

rishiga
  • 27
  • 1
  • 2
  • 8
  • 1
    You can't include a PHP file in an HTML file. You can use `include 'vote_process.php'`, but it is PHP code, so it has to be in a PHP file – Jeremy Thille Feb 24 '15 at 11:03
  • Duplicated? [link](http://stackoverflow.com/questions/20105029/include-php-file-into-html-file) and [link](http://stackoverflow.com/questions/11312316/how-do-i-add-php-code-to-html-files) See if one of this links help you. – lmarcelocc Feb 24 '15 at 11:03
  • I have been created lots of web pages in html, so only voting system purpose i could use php.. There is no way? – rishiga Feb 24 '15 at 11:05
  • @ lmarcelocc: i got the answer from this one,, http://stackoverflow.com/questions/11312316/how-do-i-add-php-code-to-html-files ,, but i just confused how to follow? – rishiga Feb 24 '15 at 11:11

3 Answers3

2

You could do with cleaning your HTML file up for a start, by storing your CSS in an external file and then add it in between the tag and the opening tag, at the top of the page:

<link href="/path/to/stylesheet.css" type="">

Then store your scripts in an external file and link that up at the bottom of the page, just above the tag, like so:

<script src="path/to/external/file"></script>

Then change your HTML file extension to .php so the PHP rendering engine knows that the file is indeed PHP.

Start using includes and require in your code. This way, you can split up all of your code into manageable modules. It's best to store all of your functions in a functions.php file and then in the index, call it at the top, above the opening html tag, with:

<?php require ('functions.php'); ?>
<html>

All of your includes should look similar, but in their own directory and looking like:

<?php include ('includes/header_inc.php'); ?>

This is how I write an include file. The _inc at the end is optional. You can leave it like

header.php

I'm new on here, so I apologise if you find it difficult to understand. Here's a link to the official page so you can get a better understanding of includes: http://php.net/manual/en/function.include.php

And for requires: http://php.net/manual/en/function.require.php

Just remember to end your php files with .php and not .html, otherwise your code will not be parsed by the PHP engine. Have a good look through the documentation after you're comfortable with the content in the included links.

  • no @nathan stephens: I need only html extension .. because i did everything in html files.. If you canexplain this link http://stackoverflow.com/questions/11312316/how-do-i-add-php-code-to-html-files ? – rishiga Feb 24 '15 at 11:38
  • Politeness doesn't cost a thing. Did you make yourself a .htaccess file? – Nathan Stephens Feb 24 '15 at 12:06
  • i can't able to understand @nathan stephens, that above link,, i need only html extension – rishiga Feb 24 '15 at 12:26
  • When the web browser renders the code in the various files included in the root folder of the site, it checks the file extensions in each of the files to understand whether a file needs to be parsed by a JavaScript engine, a PHP engine, a CSS engine, etc. Your PHP code cannot be parsed by the PHP engine because the PHP engine doesn't know there's PHP code in your HTML file. You need to change your .html to .php in order for the file to be picked up by the PHP engine. – Nathan Stephens Feb 24 '15 at 12:43
1

rename it index.php and insert php include

<?php include ("file_name"); ?>

If you really want html to work in php mode you need to enable it from server-side.

Sachin Kanungo
  • 1,054
  • 9
  • 17
0

You cannot include PHP file with javascript, cause PHP is "readable" for PHP parsers only (thats what can be included in server), but You can use Ajax for instance. http://www.ajax-tutor.com/post-data-server.html

function PostData() {
    // 1. Create XHR instance - Start
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Ajax is not supported by this browser");
    }
    // 1. Create XHR instance - End

    // 2. Define what to do when XHR feed you the response from the server - Start
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status == 200 && xhr.status < 300) {
                document.getElementById('div1').innerHTML = xhr.responseText;
            }
        }
    }
    // 2. Define what to do when XHR feed you the response from the server - Start

    var userid = document.getElementById("userid").value;

    // 3. Specify your action, location and Send to the server - Start 
    xhr.open('POST', 'verify.php');
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("userid=" + userid);
    // 3. Specify your action, location and Send to the server - End
}
kWeglinski
  • 411
  • 4
  • 14
  • may i know, how to move your answer to my existing code? thanks – rishiga Feb 24 '15 at 11:09
  • `xhr.open('POST', 'YOUR PHP FILE'); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(data);` where "data" is the info you want to send to form. @rishi – kWeglinski Feb 24 '15 at 11:13
  • these code have to add in my index.html file right? @mort – rishiga Feb 24 '15 at 11:17
  • @rishi yes and bind onclick on send button to prevent default and use function PostData(). `$('yourbutton').click(function(event){ event.preventDefault(); PostData(); }. – kWeglinski Feb 24 '15 at 11:20
  • I just confused @mort,, you have to help me.. please? – rishiga Feb 24 '15 at 11:22
  • the first function I gave you - PostData() sends form data. But it needs to be triggered somehow. So de second function calls PostData when you click the send button, but you have to pin it to your send button. (the first $(button) element. – kWeglinski Feb 24 '15 at 11:24
  • can you please provide jsfiddle link?.. i have two php files.. – rishiga Feb 24 '15 at 11:26