views:

626

answers:

3
+1  A: 

The first thing I notice, in your JavaScript code you are doing the Ajax request with $.get, and in your PHP code, you expect a POST variable if(isset($_POST['score'])).

So, if you use POST variables in the server side you should use $.post in the client side.

CMS
Ok, thanks for your reply. I just changed it, so thats one issue down..lol. But Im still experiencing the same issue. However, thank you for answering.
Lea
+1  A: 

You're not sanitizing your inputs. Anyone, using your app or not, could send you a "score", and you'll blithely put it in your database. Or they could as easily send you a SQL injection attack, by posting with score the string "1); some attack here ; insert into score(score_count) values ( 2";

tpdi
Hi there. I understand sanitization of input, and considering that i only just coded this in less than an hour ago, alot still needs to be done, including sanitizing. But I will get to that once I actually have it working..and before it goes live to my website(its sitting locally on my pc).
Lea
+9  A: 

Wow, where do I begin. Ok, I fixed up your code. Here's a list of the changes

  1. Formatted code for legibility (you need some serious discipline here)
  2. Sanitized inputs before using them in queries (prevents SQL injection)
  3. Added string delimiters to associative array key lookups (prevents E_NOTICE errors)
  4. Escaped potentially dangerous values before printing as HTML (prevents XSS)
  5. Removed awkward echo statements and changed to HTML mode for large output strings instead
  6. Updated javascript to use $.post() instead of $.get() since you read from the $_POST array at the top of the script.

Here's the code:

<?php

if ( isset( $_POST['score'] ) )
{
    $result = mysql_query( "INSERT INTO score (score_count) VALUES (" . mysq_real_escape_string( $_POST['score'] ) . " )" );
    echo $result ? 'Vote Succeeded' : 'Vote Failed: ' . mysql_error();
    exit;
}

$user_id = mysql_real_escape_string( uid() );
$m = mysql_query( "SELECT * FROM friends WHERE friend_user_id1 = '$user_id' AND friend_status != '0' LIMIT 15" );

while ( $t = mysql_fetch_array( $m ) )
{
    $fid = mysql_real_escape_string( $t['friend_user_id2'] );
    $f = mysql_query( "SELECT * FROM users WHERE user_status != '' AND user_status_date != '0' AND user_id = '$fid' ORDER BY user_status_date ASC LIMIT 15" ) or die ( mysql_error() );

    while ( $rows = mysql_fetch_array( $f ) )
    {
        $date = parse_date( $rows['user_status_date'] );
        ?>
        <div style="margin: 5px;">
            <table>
                <tr>
                    <td valign="top" style="width:55px;">
                        <a href="page.php?id=<?php echo escapeForHtml( $rows['user_username'] ); ?>">
                            <?php _photo( $rows['user_id'] ); ?>
                        </a>
                    </td>
                    <td valign="top">
                        <a href="page.php?id=<?php echo escapeForHtml( $rows['user_username'] ); ?>" class="blue">
                            <b><?php echo escapeForHtml( $rows['user_username'] )?></b>
                        </a> - <span style="font-size:7pt;"><?php echo escapeForHtml( $date )?></span>
                        <span style="font-size:7pt;"> - <a href="javascript:;" onclick="updateScore(this)" class="blue">Vote</a></span>
                        <br /><?php echo escapeForHtml( $rows['user_status'] ); ?></td><td valign="top">
                    </td>
                </tr>
            </table>
        </div>
        <?php 
    }
}

function escapeForHtml( $value )
{
    return htmlspecialchars( $value, ENT_COMPAT, 'UTF-8' );
}

?>

<script type="text/javascript">

function updateScore(answer, correct)
{
    if (answer == correct)
    {
        $.post('index.php', {'score': '1'}, function(d)
        {
            alert('Vote Accepted: ' + d);
        });
    }
}

</script>

After I got all that done, I could then clearly see that your success condition for the POST to actually take place is unknown to me. You compare answer to correct but this code snippet doesn't let me see where correct comes from. Once inside the updateScore() function I can see that answer is a reference to the HTMLAnchorElement that was clicked - but what is the source for the value sent into correct?

To be specific, I'm taking about this bolded part here

onclick="updateScore(this, correct)"

Edit!

Try this for a version of your function that updates the link after a successful vote

<script type="text/javascript">

function updateScore( answer )
{
    if ( confirm( "Are you sure?" ) )
    {
        $.post('index.php', {'score': '1'}, function(d)
        {
            alert('Vote Accepted: ' + d);
            $(answer).after("<span>You Voted!</span>").remove();
        });
    }
}

</script>
Peter Bailey
Thanks for this..my coding is terrible(lol). But im still learning, and am self-taught, so thanks for pointing all of that out. Ok, i copied this function from this comment: http://stackoverflow.com/questions/638147/updating-a-mysql-database-using-php-via-an-onclick-javascript-function/638219#638219
Lea
but what you say makes complete sense, now that i am looking over it. Could you suggest a solution of your own? Thanks sooooo much for your help:)
Lea
One of the other comments suggested using a checkbox, and hiding a submit buitton, but im abit confused about what they meant: http://stackoverflow.com/questions/712355/pass-data-to-database-using-javascript-onclick/712456#712456
Lea
Well, don't try to get this done by just copy/pasting stuff willy-nilly. Other people's work is fine for examples and reference, but if you don't understand the fundamentals of whats going on, then you are doomed to many late nights.
Peter Bailey
Other than a button-click, do you know under what scenario you want the vote to be saved? To not be saved?
Peter Bailey
Ok.. I honestly am so brand new to javascript, I havent the slightest idea what i am doing. And because my php isnt completely upto scratch, trying to take on another language at this point is just too confusing for me. But you would be surprised with wat I have achieved, just copying and pasting.
Lea
I updated my answer with some new code
Peter Bailey
Ok, thanks. I applied the changes you made..including the code you cleaned. But i am still getting nothing upon clicking the link.
Lea
You'll need to do a little more due-diligence before I can help you more. Are you getting a javascript error? If so, what's the error message? Is the onclick firing at all? (onclick="alert('test');"). If the click is firing, is your vote page failing? (use an HTTP sniffer like Firebug or Charles)
Peter Bailey
Ok, my apologies..thank you for being patient. There is nothing happening after I click the link. No error message. Yes, onclick fires perfectly. And i will need to do a browser restart to enable my firebug. So ill be back. Thanks again so much.
Lea
Ok. Firebug shows too errors upon onclick firing: correct is not definedonclick(click clientX=577, clientY=318)WQgeIXGh...7xA%3D%3D (line 2)[Break on this error] updateScore(this, correct); AND it outputs a syntax error where javascript(void); is used.
Lea
Try the updated link (modified my post)
Peter Bailey
Ok, wonderful. That made the magic happen..lol. But I dont think it completes right through to posting the data. 1. I click the link, a dialog opens asking if im sure? 2. I click "yes", and another dialog opens and says "vote accepted:" and it shows the source of the page in the dialog...cont.
Lea
but there is so much source, that i cannot see the end of the dialog box, and am not sure if there is an extra confirmation? I do not see the "You voted!" alert either.
Lea
OK.. I just used the IE tab add-on to view the dialog minimized as it wouldnt minimize in FF properly, and the dialog had a final confirmation.."ok"..button. But nothing happened in the database.
Lea
Answer updated again. I modified it to return custom output when the vote is POSTed.
Peter Bailey
Ok, that works! Thank you soo much!! I do get one error though: answer.after is not a functionLine 237Also, there is a mispelt function in the posting code: (" . mysq_real_escape_string( $_POST['score'] )... but aside from that..all is working great!..
Lea
Oh ya - try $(answer).after instead
Peter Bailey
Lea
My pleasure. For what it's worth, I'm self-educated too. So keep at it and have fun!
Peter Bailey