0

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.

1
  • you need to echo or return the data from myCode.php and get it into JS and use it for further processing. Commented Jan 12, 2021 at 16:24

2 Answers 2

2

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
        }
    });
Sign up to request clarification or add additional context in comments.

4 Comments

Don't add async:false - that's deprecated and it causes poor user experience by locking the UI while Ajax is happening. You don't need it anyway - the response can be received in the .done() callback in the normal, asynchronous way, without degrading the performance of the site.
He asked to wait for an answer, so I offered it. I deleted this line, thanks for the comment
Sure they asked that, but that doesn't mean we should teach bad practice. Instead, OP should learn the concepts of writing async code in the right way. Thanks for deleting it, have an upvote :-)
you are not using the correct syntax for .done(). See here for details
0

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.

5 Comments

Thanks for your suggestion. Unfortunately, it doesn't work for me: pastebin.com/HfT4BFmW Nothing is logged to console. Any other ideas? Am I doing it wrong?
Hmm. Somehow it works without dataType: 'json'. That makes no sense to me. When logging data.status, however, I just get the responsecode (200).
Without dataType it uses intelligent guessing. You can omit it
The problem with omitting is that it doesn't output the variable. Let's say I called it $test. Logging data.test just throws an undefined error. Placing exit(); after my echo seems to solve the issue and I'm now able to use the variables in jQuery. But why?
Don’t know how to debug without a closer look at your code

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.