简体   繁体   中英

PHP $_SERVER['REQUEST_METHOD'] always returning GET with AJAX post

I am trying to set up an api for my website. I would like to have a single page that does a different action depending on the request method. ie. GET to get a resource, POST to create a new one, PUT to update and DELETE to delete. I am testing the $_SERVER['REQUEST_METHOD'] variable to see which function I should run but for some reason it is always showing as get regardless of my ajax request.

Page 1

var data = {
            store_id: id,
            reward: reward,
            disclaimer: disclaimer,
            period: period,
            active: active
        }

        //make request to save item
        $.ajax({
                type: "POST",
                url: 'http://' + '<?php echo $base_url; ?>' + 'api/birthday',
                data: data,
                dataType: 'json',
                //headers: {"X-HTTP-Method-Override": "POST"},
                success: function(obj){
                    console.log(obj);
                    $('#save-modal').dialog('open');
                },
                error: function(xhr, textStatus, errorThrown){
                    console.log(arguments);
                    console.log(xhr + '' + textStatus + ' ' + errorThrown);
                }
        });

Page 2

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if( isset($_REQUEST['store_id']) &&
        isset($_REQUEST['reward']) &&
        isset($_REQUEST['disclaimer']) &&
        isset($_REQUEST['period']) &&
        isset($_REQUEST['active']) &&
        is_numeric($_REQUEST['active'])){
            exit(json_encode(update_birthday_reward(filter_var($_REQUEST['store_id'], FILTER_SANITIZE_NUMBER_INT), filter_var($_REQUEST['reward'], FILTER_SANITIZE_STRING), filter_var($_REQUEST['disclaimer'], FILTER_SANITIZE_STRING), filter_var($_REQUEST['period'], FILTER_SANITIZE_STRING), filter_var($_REQUEST['active'], FILTER_SANITIZE_NUMBER_INT))));   
    }else{
        exit(json_encode($_SERVER['REQUEST_METHOD']));
    }
}else if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if(isset($_REQUEST['store_id'])){
        exit(json_encode(get_birthday_reward($_REQUEST['store_id'])));  
    }else{
        exit(json_encode($_SERVER['REQUEST_METHOD']));
    }
}

Looks like your request is being redirected to an actual PHP file, that's why you get POST first, which immediately translates to a GET request.

Try adding actual PHP file, like .../birthday/index.php , instead of .../birthday/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM