s_puria
s_puria

Reputation: 407

laravel Ajax success function not working

I send a store request to my laravel application through AJAX. The controller function works properly, but either I cannot get a success message in my ajax function, or the function on success is not working.

Ajax code:

$.ajax({
    type: "POST",
    url: 'http://127.0.0.1:8000/dreams',
    data: {
        description: description,
        offset_top: offset_top,
        offset_left : offset_left
    },
    success: function(msg){
        console.log("done");
    }
});

Controller's store function:

public function store(Request $request)
{
    echo $request;
    if (Auth::check()) {
        $user = Auth::user();
        $dream = new Dream($request->all());
        if ($dream) {
            $user->dreams()->save($dream);
            $response = array(
              'dream' => $dream,
              'status' => 'success',
              'msg' => 'Setting created successfully',
            );
            return \Response::json($response);
        }
        return \Response::json(['msg' => 'No model']);
    } else {
      return \Response::json('msg' => 'no auth');
    }
}

Upvotes: 0

Views: 5094

Answers (2)

AddWeb Solution Pvt Ltd
AddWeb Solution Pvt Ltd

Reputation: 21691

Try below code for store method:

public function store(Request $request)
{
    if (Auth::check()) {
        $user = Auth::user();
        $dream = new Dream($request->all());
        if ($dream) {
            $user->dreams()->save($dream);
            $response = array(
              'dream' => $dream,
              'status' => 'success',
              'msg' => 'Setting created successfully',
            );
            return \Response::json($response);
        }
        return \Response::json(['msg' => 'No model']);
    } else {
      return \Response::json(['msg' => 'no auth']);
    }
}

Upvotes: 1

Naushil Jain
Naushil Jain

Reputation: 444

Try to pass data in ajax using this way.

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

$.ajax({
    type: "POST",
    url: 'http://127.0.0.1:8000/dreams',
    data: {
        description: description,
        offset_top: offset_top,
        offset_left: offset_left
    },
    success: function(msg) {
        console.log("done");
    }
});

Upvotes: 2

Related Questions