Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

adrian3ka's avatar

AJAX Post request 500 internal server error

Good morning everyone,

I try to use AJAX on post method, but if i make the script on the main php file everything goes fine, but if i make it script src="....." it has 500 internal server error

This is the route

Route::post('/answer',function(){
    $user = User::find(Request::get('idUser'));
    $game = Game::find(Request::get('idGame'));
    $action = 'Input : ' . Request::get('answer') . ' - Answer : ' . $game->word . ',';
    $result;
    if(strcasecmp(Request::get('answer'),$game->word) == 0){
        $action .= ' Got 100';
        $user->score += 100;
        $result = 'Correct, you got 100 points!!';
    }else{
        $action .= ' Minus 100';
        $user->score -= 100;
        $result = 'Oops, minus 100 points!!';
    }
    $user->update();
    $log = array('id_user' => Request::get('idUser'), 'action' => $action );
    Gamelog::create($log);
    $return = array('username' => $user->name , 'score' => $user->score, 'result' => $result);
    return Response::json($return);
});

This is the ajax code

$.ajax({
    url: "answer",
    type: "POST",
    data: { answer:ans , idGame:id , idUser:iduser , _token:CSRF_TOKEN},
    success:function(data){
        $('#info').text(data.result);
        $('#userScore').text('Score : ' +data.score);
        if(data.result == "Correct, you got 100 points!!"){
            $('div#info').addClass('btn-success');
            $.getJSON('getRequest',function(data){
                $('#getRequestData').text(data.word);
                $('#questionId').text(data.id);
                $('#hint').text(data.hint);
                $('#wordAnswer').val("");
            });
        }else{
            $('div#info').addClass('btn-danger');
        }
    },error:function(){ 
        alert($('#_token').val());
    }
}); //end of ajax

all of the things is well defined on the route, crsf_token because it gone well if I make the js on the php file. But if i separate on diffrent js file, it has 500 internal error.

Anyone have this problem before?

0 likes
2 replies
Cronix's avatar

Try putting a slash at the start of the 2 urls that you are using ajax for.

url: "/answer",
// ...

$.getJSON('/getRequest',function(data){

I'm not sure why you're making 2 separate ajax calls. It seems you could pass that data back that you're getting from /getRequest in the initial ajax call.

Please or to participate in this conversation.