0

I'm a beginner with JavaScript, what I need to do is to show a div with an alert in case of a certain string in the results data after a JavaScript function has been executed.

Here's my code (I'm working with Parse PHP SDK):

comments.php

echo '
      <h5>'.$topic.'</h5>

      <div style="display:none;" id="anAlert" class="alert alert-danger"> 
      <button type="button" class="close" data-dismiss="alert">×</button> <strong>Ouch!</strong>
                You already upvoted this Topic!
            </div>
            <br>
            ';

Javascript code into comments.php:

// UPVOTE A TOPIC -------------------                                      
function upvoteTopic() {
    var topicID = "<?php echo $topicID ?>";
    var votesNr = Number("<?php echo $votes ?>"); 

    $.ajax({
        url:"vote-topic.php?isUpvoted=true&topicID=" + topicID, // Call vote-topic.php 
        type: "GET", 

        success:function(data) {
            var results = data
            console.debug(results);

            if (results !== 'You already upvoted this Topic') {

                // Show updated votes
                document.getElementById('votesTxt').innerHTML = votesNr;

                // Change buttons style
                $( "#upvoteTopicButt" ).removeClass( "btn-default" ).addClass( "btn-primary" );
                $( "#downvoteTopicButt" ).removeClass( "btn-primary" ).addClass( "btn-default" );

            } else {
                document.getElementById("anAlert").style.display = 'block';
            }

    }});
}

vote-topic.php

// UPVOTE ------------------------------------------
if ($isUpvoted == "true") {

    // CANNOT VOTE YOUR OWN TOPIC
    if($userPointer->getObjectId() == $currUser->getObjectId()) {
        echo 'You cannot vote your own Topic!';

    // VOTE TOPIC
    } else {

        // Get votes array
        $upvotedBy = $tObj->get('upvotedBy');
        $downvotedBy = $tObj->get('downvotedBy');

        // You already upvoted this Topic
        if (in_array($userID, $upvotedBy)) {

            echo 'You already upvoted this Topic'; // HERE'S THE LINE I NEED TO COMPARE IN THE IF STATEMENT OF MY JAVASCRIPT FUNCTION!

        // UPVOTE TOPIC
        } else {
            array_push( $upvotedBy, $currUser->getObjectId() );
            $downvotedBy = array_diff( $downvotedBy, array($currUser->getObjectId() ) );

            // Increment votes
            $tObj->increment("votes", 1);
            $tObj->setArray('upvotedBy', $upvotedBy);
            $tObj->setArray('downvotedBy', $downvotedBy);
            $tObj->save();

            // echo 'You upvoted this Topic!';
        }
    }

So, when I click the UPVOTE button, my Javascript function successfully calls the vote-topic.php script and performs the saving in there, it changes the style of the upvoteTopicButt and downvoteTopicButt buttons, but it doesn't display my anAlert div.

I've tried to launch an alert of results, and it actually shows this line:

You already upvoted this Topic

So that's why I've placed this IF statement into my Javascript function:

    if (results !== 'You already upvoted this Topic') {
      ...

    } else {
        document.getElementById("anAlert").style.display = 'block';
   }

In theory, when the results message is == You already upvoted this Topic, my function should show my anAlert div. But it doesn't.

What am I doing wrong?

4
  • 1
    You are missing a semicolon in comments.php script part: var results = data <- doesnt have ';' Commented Oct 18, 2017 at 10:01
  • Are you sure it isn't jumping to the else statement? Have you tried putting a console message there tot see if js reaches that part? Commented Oct 18, 2017 at 10:05
  • @RolandRuul I've added the semicolon, but the issue is still there. Commented Oct 18, 2017 at 10:08
  • @Michel I did, but the console doesn't print anything... I don't know why :( Commented Oct 18, 2017 at 10:16

1 Answer 1

1

Compare vote-topic.php response as a result may be tricky if you have undesired char before or after your string. You can return a JSON or working with HTTP response code to "throw" an error.

For example with different error code:

Change echo 'You already upvoted this Topic'; by http_response_code(418);

Then, in your javascript file, add an error function like:

$.ajax({
    url:"vote-topic.php?isUpvoted=true&topicID=" + topicID, // Call vote-topic.php 
    type: "GET", 

    success:function(data) {
        var results = data
        console.debug(results);

        // Show updated votes
        document.getElementById('votesTxt').innerHTML = votesNr;

        // Change buttons style
        $( "#upvoteTopicButt" ).removeClass( "btn-default" ).addClass( "btn-primary" );
        $( "#downvoteTopicButt" ).removeClass( "btn-primary" ).addClass( "btn-default" );
    },
    error: function () {
        document.getElementById("anAlert").style.display = 'block';
    }
});

See jquery ajax doc

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, it works like a charm. One thing though, if I click the upvote button once, it shows the alert, but if I close the alert and click the upvote button again, the alert doesn't show up again...
When you close the alert, it may be remove from the DOM and not hidden. You can solve it by duplicating your alert when you want to display it, and keeping the original one hidden
may i ask you one more thing? I have this button: <button class="btn btn-danger btn-sm" onclick="reportTopic('.$topicID.')"> which has to call this JS function: function reportTopic(topicID) but it doesn't, it prints me this message in the console: Uncaught ReferenceError: CRFYLtWNDD is not defined at HTMLButtonElement.onclick
You forget some ' or " in your function call: <button class="btn btn-danger btn-sm" onclick="reportTopic(\''.$topicID.'\')"> Note the 2 \' in reportTopic. Now the argument is considered as a string, not a JS var.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.