Maris Maris - 1 month ago 5
jQuery Question

jQuery execute php script on button click and analyse results?

TASK: When button is clicked - it disables button, executes PHP script. Based on the value PHP script returns - I want to perform one of two actions!

1) if php returns "OK", I would like to simply reload the current page;

2) if php returns "NOTOK:NotOkText", I would like to fill #updateresult div with NotOkText, Reenable the button.

<button id="updatebutton" onclick="update_btn_click('params');">Execute PHP</button>


And here's the jQuery I have so far. Obviously it is nowhere near doing what i want. It just loads the DIV with the output of php and it doesn't even wait while loading finishes (PHP will try to fetch data from another server, it will take some time) - it immediately re-enables the button.

function update_btn_click(param) {

$('#updatebutton').prop("disabled",true);
$('#updatebutton').text("Processing...");


$("#updateresult").load("/update.php");

//how to wait for result and analyse what has been returned?

//act upon result

$('#updatebutton').removeAttr('disabled');}

Answer
function update_btn_click(param) {
    $('#updatebutton').prop("disabled",true);
    $.ajax({
        url:"update.php",
        type:"post",
        success: function(response){
            if(response=='Ok') {
                location.reload();
            } else {
                $("#updateresult").html('error');
                $('#updatebutton').prop("disabled",false);
            }
        },
        error: function(response){
            console.log('could not fetch data');
        },
        complete: function(response){
            // hide loading
        }
    });
}

in update.php

if(action) {
    echo 'Ok';
} else {
    echo 'error';
}