I would like to receive the return value from the function of aax then.

Asked 2 years ago, Updated 2 years ago, 77 views

In Ajax(jQuery), I want to use the return value from the function in then or done in subsequent programs after then, but it doesn't work.
I've tried many things like returning the result.then itself, but I'm ashamed to say I don't know.

Ajax's own communication is a prerequisite.
I'm sorry, but I'd appreciate it if someone could tell me.

The following code is omitted:

<script src="../js/jquery/jquery-3.3.1.min.js"></script>

<script>
function ajax_func(post){
        return$.ajax({
        type: 'POST',
        url: 'ajax.php',
        cache: false,
        dataType: 'json',
        data: {
            'greeting': post
        }
        })
    }

var post = 'Hi';
console.log(post);
var result=ajax_func(post);

result.then(
    function(data){
        console.log(data);
        if(data!=""){
            return true;//(1) I want to receive this true
        }
    }
)
//(2) I want to write the process of receiving the true

</script>

ajax.php

<?php
header("Access-Control-Allow-Origin:*");

if(isset($_POST)){
    echo json_encode('Hello');
}

The return value is //(1) where you want to receive this true and
The subsequent action you want to write is the action you want to write to receive //(2)true

.

I also checked the question that seems similar, but
It's not quite right.

Get the Ajax return value

php jquery ajax

2022-09-29 21:31

2 Answers

You can connect it with then.

result
        .then(function(data){
          console.log(data);
          if(data!=""){
            return true;//(1) I want to receive this true
          }
        })
        .then(function(retVal){
          //(2) I want to write the process of receiving the true
          console.log("retVal:" + retVal);
        });

As found in jQuery.ajax()>The jqXHR Object, the format is Promise.


2022-09-29 21:31

I solved myself using this number one method.
I am very sorry if anyone is preparing an answer.

How to use ajax() in jQuery to get a return value - Qiita


2022-09-29 21:31

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.