Aminesrine
Aminesrine

Reputation: 2140

jQuery $.ajax post to PHP in the same file not working

This the code:

<script>
$( document ).ready(function() {

    $( ".button" ).click(function() {

        var clickBtnValue = $(this).val();
        $.ajax({
            //url: '', // url is empty because I'm working in the same file
            data: {'action': clickBtnValue},
            type: 'post',
            success: function(result) {
            alert("action performed successfully"); //this alert is fired
            }

    });

});
});
</script>

<div>Button clicked:
<?php 
if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'insert':
            echo "select button!";
            break;
        case 'select':
            echo "insert button!";
            break;
    }
}
?>
</div>

<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />

In the inspector I can see a posted value, so why echo "insert button!"; or echo "select button!"; are not working?

Upvotes: 1

Views: 11029

Answers (1)

Aly
Aly

Reputation: 458

You must change the content in the div in the javascript, as you're doing with the alert(). If you're working on the same file, the PHP should be at the beginning of the file.

<?php 
if (isset($_POST['action'])) {
    switch ($_POST['action']) {
        case 'insert':
            echo "insert button!";
            break;
        case 'select':
            echo "select button!";
            break;
    }
    exit;
}
?>

<script>
$( document ).ready(function() {
    $( ".button" ).click(function() {
        var clickBtnValue = $(this).val();
        $.ajax({
            //url: '', // url is empty because I'm working in the same file
            data: {'action': clickBtnValue},
            type: 'post',
            success: function(result) {
                alert("action performed successfully"); //this alert is fired
                $('div#result').text('Button clicked: ' + result);
            }
        });
    });
});
</script>

<div id="result"></div>

<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />

Upvotes: 7

Related Questions