Dennis
Dennis

Reputation: 56

Get variable value from PHP in AJAX

I'm trying to catch a PHP variable in AJAX, but I'm not having much luck.

myCode.php

<?php

//myFunction that will return a status
if(myFunction() === true){
    $status = "success";
}else{
    $status = "failure";
}
?>

In my HTML, I have the following:

<script>
    function initiate_delete() {
        $.ajax({
            url: '{$modulelink}&action=delete',
            type: "post",    //request type,
            dataType: 'json',
            data: {
                type: 'test'
            }
        });
    }
</script>

Is there any way to have AJAX wait for the PHP to execute and then get $status when I execute initiate_delete?

Thanks in advance.

Upvotes: 0

Views: 62

Answers (2)

Lelio Faieta
Lelio Faieta

Reputation: 6667

Your PHP needs to return the value. If you want to keep the dataType Json (suggested) you just need to json_encode your output.

So the PHP becomes:

<?php
$type=$_POST['type'];
//myFunction that will return a status
if(myFunction() === true){
    $status = "success";
}else{
    $status = "failure";
}
echo json_encode('status'=>$status);
?>

Then you need to tell Ajax what to do with the answer received using .done() So your Ajax will become:

$.ajax({
    url: '{$modulelink}&action=delete',
    type: "post",    //request type,
    dataType: 'json',
    data: { type: 'test'}
}).done(function(data){
    console.log(data.status);
});

Now you can do what you want with status but only in the .done() function. The rest of your js will be executed without waiting for ajax to return a value since it is asyncronous. So add here all the logic like dom manipulation and so on depending on this response.

Obviously you can have more data returned by php in the json and acccess them by key as done for status.

Upvotes: 0

Eden Moshe
Eden Moshe

Reputation: 1147

Change code to

<?php

//myFunction that will return a status
if(myFunction() === true){
    $status = "success";
}else{
    $status = "failure";
}
echo $status

or short it to

 echo myFunction() ? "success" : "failure";

To wait for an answer - you can execute the request asynchronously, and get the result in the .done() callback

$.ajax({
        url: $(this).attr('href'),
        type: 'POST',
        fail: function(){
            //do something
        },
        done: function(m){ 
           /// do something else
        }
    });

Upvotes: 2

Related Questions