Daniel
Daniel

Reputation: 3272

Writing if/else statement in AJAX

I've been messing around with this application:

gamble.php:

function gamble() {
    $chance = rand(1, 100);

    if ($chance <= 40) {
        echo "win";
    } else {
        echo "lose";
    }
}
gamble();

HTML:

<button type="button" class="btn">Click Me</button>

jQuery:

$(document).ready(function() {
    $(".buy_btn").click(function() {
        $.ajax({
            type: 'POST',
            url: 'scripts/gamble.php',
            success: function(data) {
                if (data == "win") {
                    alert("You win");
                } else {
                    alert("You lose");
                }
            }
        });
    });
});

Why won't this if/else statement work?
It's set out exactly like a JavaScript if/else statement should be, is it because it's jQuery/AJAX? How can I fix it?


I also have another question:

Inside the PHP document instead of echoing, I can return data instead. However how do I use this returned data in AJAX?
I've tried using if/else statements to undertake dynamic events based on the returned data, however it doesn't work.

Upvotes: 1

Views: 3558

Answers (4)

Daniel
Daniel

Reputation: 3272

I fixed it by changing the output to numbers instead:

script.php:

if ($chance <= $win_c) {
    echo 0;
} else {
    echo 1;
}

javaScript:

<script type="text/javascript">
                $(document).ready(function() {
                    $(".buy_btn").click(function() {
                        $.ajax({
                            type: 'POST',
                            url: 'scripts/gamble.php',
                            success: function(data) {
                                if (data == 0) {
                                    alert("You win!");
                                } else if (data == 1) {
                                    alert("You lose");
                                }
                            }
                        });
                    });
                });
</script>

Why does it require a number instead of a string to work though? I tried using String(); to convert it to a pure string, however that didn't work either

Upvotes: 0

Neo
Neo

Reputation: 407

your code is right... just one minor thing need to keep in mind ...

gamble.php:

<?php 
function gamble() {

    $chance = rand(1, 100);

    if ($chance <= 40) {
        echo "win";
        exit;      //line added
    } else {
        echo "lose";
        exit;      //line added
    }

}
gamble();
?>

HTML:

<button type="button" class="btn">Click Me</button>

jquery:

<script type="text/javascript">
            $(document).ready(function() {
                $(".btn").click(function() {
                    $.ajax({
                        type: 'POST',
                        url: 'scripts/gamble.php',
                        success: function(data) {
                            if (data == "win") {
                               alert("You win");
                            } else {
                               alert("You lose");
                            }
                        }
                    });
                });
            });
</script>

whenever you want any response through ajax and if you want to use echo then don't forget to add exit

using above given code the alert will surely appear after clicking the button .. and yeah I have also used same class in jquery as given to the button in your HTML code ... good luck

Upvotes: 0

Pupil
Pupil

Reputation: 23978

Simple typ:

$(".buy_btn").click(function() { // You called script on this.

Should be

$(".btn").click(function() { // This is actual class of the element.

Otherwise, code is fine.

Also, you can optimize your gamble() function as following:

function gamble() {
  echo (rand(1, 100) <= 40) ? 'win' : 'lose';
}

Suggestions implemented:

1) $chance is used only once, so instead of using $chance, we can use rand(1, 100).

2) Use of ternary operator.

Upvotes: 3

Shitiz Garg
Shitiz Garg

Reputation: 605

Inside the PHP document instead of echoing, I can return data instead. However how do I use this returned data in AJAX? I've tried using if/else statements to undertake dynamic events based on the returned data, however it doesn't work.

See outputting JSON data via PHP and using this data in your AJAX callback in order to handle data via jQuery. You can't use return statement since it's not a PHP function call per-se, you're calling a web-page which outputs it's data to the JS AJAX call. You can JSON encode (via json_encode(array $data)) function which is easily readable (and is most likely automatically parsed by jQuery, see jQuery.ajax docs on how to handle that callback).

Basically, you call $.ajax -> browser sends a request to server which parses the query and calls the PHP function -> PHP function processes data and outputs it using JSON -> browser reads the JSON output, jQuery parses it into object data -> passes it to your callback function where you do your processing.

Upvotes: 0

Related Questions