Search code examples
jqueryajaxpostmethodsget

Something wrong with data sent when using AJAX with method POST


I'm trying to use AJAX with POST. Originally the method is GET and it works. But when I change method to POST, I discover that the receiving server receives data as null. What could be my problem? The code is simple and I don't understand why it's gone complicated when I change method from "GET" to "POST".

            $.ajax({
                method:"POST",  //Originally GET
                url:"/administrator/change_member_id/",
                timeout:30000,  //30 seconds
                data:{
                    "m_as_id": storeID,
                    "m_id": pad_id("UMID", memberID)
                }
            })
            .done(function(responsedata) {
                var parsedJson = $.parseJSON(responsedata);

                if(parsedJson.result==1) {
                    $("#"+storeID+"_member_id_a").text(pad_id("UMID", memberID));
                    $("#"+storeID+"_member_id_b").text(pad_id("UMID", memberID));
                    alert("Success");
                } else {
                    alert(parsedJson.title+"\n"+parsedJson.description);
                }
            })
            .fail(function(xhr, status, errorThrown) {
                alert("Error communicating with server!");
                console.log("Status: "+status);
                console.log("Error: "+errorThrown);
            })
            .always(function() {
            });

Solution

  • It turns out I didn't change "get" to "post" in my route using the Laravel framework. I had:

    Route::get('/administrator/change_member_id', 'AdministratorController@changeMemberID')->middleware(CheckLogin::class);
    

    It needed to be:

    Route::post('/administrator/change_member_id', 'AdministratorController@changeMemberID')->middleware(CheckLogin::class);
    

    I then stumbled across another problem where I couldn't connect to the server at all. It turns out the URL in AJAX wasn't accurate enough. I had:

    url:"/administrator/change_member_id/"
    

    But it needed to be the exact same as the route's (above), which didn't have a slash at the very end:

    url:"/administrator/change_member_id"
    

    I then played around a bit and realised that the URL in AJAX will result in an connection error if I have a slash at the very end regardless of the URL in route. The URL in route can or cannot have a slash at the very end. So I don't know whether this is because of POST technicalities with URL like how GET uses query string (will have slash at very end) and POST doesn't. Or perhaps it's some kind of bug in AJAX design that causes POST to be not as flexible as GET here?

    EDIT: Since I'm using Laravel framework, I think there's such thing as CSRF protection so I had to add either one of:

    data: {
        _token: "{{ csrf_token() }}"
    },
    

    or:

    headers: {
        "X-CSRF-TOKEN": "{{ csrf_token() }}"
    }