weixin_33739523 2017-10-20 16:00 采纳率: 0%
浏览 42

从Ajax返回值[重复]

This question already has answers here:
                </div>
            </div>
                    <div class="grid--cell mb0 mt4">
                        <a href="/questions/14918462/get-response-from-php-file-using-ajax" dir="ltr">Get response from PHP file using AJAX</a>
                            <span class="question-originals-answer-count">
                                (5 answers)
                            </span>
                    </div>
            <div class="grid--cell mb0 mt8">Closed <span title="2017-10-20 16:39:05Z" class="relativetime">2 years ago</span>.</div>
        </div>
    </aside>

I'm new to programming and i'm not good at all with Ajax.
I want to get a value back from a php script in Ajax.
I send a javascript variable to a php script like that :

 $('#deleteSelectedButton').on('click', function () {
    if (confirm('Do you want to suppress the messages ?')) {
        $.ajax({
            type: 'POST',
            url: 'suppression-message',
            data: {
                'checkboxIdArray': checkboxIdArray.toString(),
            }
        });
        return false;
    }
});  

This is sent to the following php script which is deleting messages according to the id contained in the checkboxIdArray:

if (isset($_POST['checkboxIdArray'])) {

    $checkboxIdArray = $_POST['checkboxIdArray'];
    $str = json_encode($checkboxIdArray);
    $tab = explode(",", $str);
    $deleteSuccess = true;

    foreach($tab as $id)
    {
        $id = filter_var($id, FILTER_SANITIZE_NUMBER_INT);
        if (!$messageModelDb->delete($id)) {
            $deleteSuccess = false;
            die();
        }
    }
    if ($deleteSuccess === true) {
        $message = 'Success';;
    } else {
        $message= "Error";
    }
}

I want to get the $message variable back to my javascript in order to display a message according to the result of the script.

I would really appreciate some help ...
Thank you.

</div>
  • 写回答

5条回答 默认 最新

  • weixin_33743661 2017-10-20 16:03
    关注

    You have to use success function and actually include the message in the response

     $.ajax({
                type: 'POST',
                url: 'suppression-message',
                data: {
                    'checkboxIdArray': checkboxIdArray.toString(),
                },
                success : function(response){
                  // your code or logic
                  alert(response);
                }
            });
    

    PHP

    if ($deleteSuccess === true) {
        $message = 'Success';
    } else {
        $message= "Error";
    }
    echo $message;
    
    评论

报告相同问题?