当请求方法是GET但在POST方法中失败时,为什么这个ajax请求成功

当请求方法是GET但在POST方法中失败时,为什么这个ajax请求成功

问题描述:

When I set the request type to "GET",(and also use $_GET on server side), it successfully fetches the response, but gives a 400 error, Missing required parameters: student_id when I set the type to POST.

Here's the code :

$.ajax({
        type: "GET",
        url: "?r=fees/fees/transactions",
        dataType: "json",
        data: { student_id: student_id },           
        success:function( msg ) { 
            console.log(msg);
        },
        error: function(xhr, ajaxOptions, thrownError){
            console.log("failed");
            console.log(xhr.responseText);
            console.log(ajaxOptions);
            console.log(thrownError);    
        }
});

Here is the request URL when I set the request method to GET:

http://localhost/demo.git/index.php?r=fees/fees/transactions&_csrf=bEJJWVowdl8jBwQjaUMsAA52eT8MXBMLJigwHTxeKSlVKyxoD2o5KQ%3D%3D&student_id=10115".

why doesn't this work when I set the above request type to POST and receive the variable on server side by POST method?

Here is the server side action (I am using Yii2 MVC framework)

public function actionTransactions($student_id){
    $student_id = $_POST['student_id'];
        ...
        ...   
    echo json_encode($response);

}

Your function need param $student_id from GET method. If youre using AJAX to send request, using data: { 'student_id': student_id }, - it will be added to your URL where AJAX is sent.

If you want to use POST method, you have to modify your URL:

url: "?r=fees/fees/transactions?student_id=" + student_id,

And remove data key.

Second solution is to remove $student_id param from your actionTransactions, then system will accept requests without $student_id in GET, but you will have to ensure, that it's in $_REQUEST.