Mikle
Mikle

Reputation: 15

Laravel JQuery AJAX POST get data

I have a code:

var bet = {
    tournament: '',
    bo: '1',
    bet_team: '2',
    betted: '3',
    potential: '4',
    percent: '5'
};

$.ajax({
    type: 'POST',
    url: '/api/makeBet/',
    data: bet,
    contentType: 'application/json',
    dataType: 'json',
    success: function(data) {
        if(data.error) {
            sweetAlert("Oops...", data.data, "error");
        } else {
            sweetAlert("Success!", data.data, "success");
        }
    },
    error: function(html, status) {
        console.log(html.responseText);
        console.log(status);
    }
});

But when I'm trying to get $request->tournament or something else, I'm getting nothing.

Upvotes: 1

Views: 4605

Answers (3)

silvedo
silvedo

Reputation: 121

This worked for me

function filter_by_department()
{
    var bet = {
    tournament: '',
    bo: '1',
    bet_team: '2',
    betted: '3',
    potential: '4',
    percent: '5'
};
var token;
token='{{ csrf_token() }}';
console.log(token);
$.ajax({
   headers: {
      'X-CSRF-TOKEN': token
},
    type: 'POST',
    url: 'task_department',
    data: bet,
    dataType: 'html',
    success: function(data) {
        if(data.error) {
            sweetAlert("Oops...", data.data, "error");
        } else {
            console.log(data);

        }
    },
    error: function(html, status) {
        console.log(html.responseText);
        console.log(status);
    }
});
}

Upvotes: 1

Matthew Alika
Matthew Alika

Reputation: 379

There are many probable causes of your error.

  • your route
  • your controller
  • your tournament is empty

Posting your code can go a long way; meanwhile, this might be of help:

Route...

Route::post('/api/makeBet/', 'YourController@index');

Controller...

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class YourController extends Controller
{
    //
    public function index(Request $request)
    {
        $tournament = $request->tournament //gives tournament
    }
}

Upvotes: 2

Burdy
Burdy

Reputation: 611

You need to use JSON.stringify to first serialize your object to JSON, and then specify the content-type so your server understands it's JSON. This should do the trick:

var bet = {
    tournament: '',
    bo: '1',
    bet_team: '2',
    betted: '3',
    potential: '4',
    percent: '5'
};

$.ajax({
    url: '/api/makeBet/',
    method: 'post',
    contentType: 'application/json',
    data: JSON.stringify(bet),
    success: function(data) {
           // so something        
    }
})

Upvotes: 0

Related Questions