Home > Blockchain >  What is missing in my ajax post request that fails to return a 200 response?
What is missing in my ajax post request that fails to return a 200 response?

Time:09-27

Can someone tell me what's missing in my ajax request? I originally thought it was the _token but I still don't get a 200 response. Maybe it's a missing parameter in my function? Below is my code, built on Laravel.

View.blade.php

callback: function (result) {
            if(result == true){
                $('#common_loader').show();
                $.ajax({
                    method:'POST',
                    data: {'offer_id': offer_id,'_token':'{{ Session::token() }}'},
                    cache: false,
                    url: "{{url('/chooseArtist')}}",
                     success: function (data) {
                        $('#common_loader').hide();
                        var rep = JSON.parse(data);
                        if (rep.status == 200) {
                            bootbox.alert(rep.response);
                        /// code continues. 

Route

Route::post('/chooseArtist', [ProjectController::class, 'chooseArtist']);

Controller Function

public function chooseArtist() {
$data["status"] = 200;
echo json_encode($data);
                die;
}

CodePudding user response:

I don't think you can include the CSRF token that way on more recent versions of Laravel? Include it in the meta tag of your page :

<meta name="csrf-token" content="{{ csrf_token() }}" />

And then incorporate it into your script before your Ajax call :

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

Separately, on the frontend you're trying to bootbox alert "rep.response" but on the back end your response only contains the status, not anything else. Also, rather than echo it, you should return the result.

$data = array();
$data['status'] = 200;
$data['response'] = "Jimi Hendrix";
return (json_encode($response));

CodePudding user response:

Laravel post request csrf token in data attribute.

Try this solution:

callback: function (result) {
   if(result == true){

        var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');

                $('#common_loader').show();
                $.ajax({
                    method:'POST',
                    data: {_token: CSRF_TOKEN,'offer_id': offer_id,'_token':'{{Session::token() }}'},
                    cache: false,
                    url: "{{url('/chooseArtist')}}",
                     success: function (data) {
                        $('#common_loader').hide();
                        var rep = JSON.parse(data);
                        if (rep.status == 200) {
                            bootbox.alert(rep.response);
                        /// code continues. 
  • Related