rushtoni88
rushtoni88

Reputation: 4665

Laravel - How to call a controller function via AJAX (jQuery)

I have a number of working controller functions, however, for usability I want to switch some of them over to be called via AJAX.

Here is my jQuery code:

$.ajax({
        method: 'GET',
        url: $(this).data('url'),
        data: {},
        success: function( response ){
            console.log( response );
        },
        error: function( e ) {
            console.log(e);
        }
    });

And here is my controller function:

public function add( $user_id, $project_id )
{

    $project = Project::findOrFail( $project_id );

    if( empty( $project ) ) {

        return view( 'home' )->with('message', 'Sorry, user not found');

    }

    if ( $project->user_id != $user_id ) {

        $scrapbook = Scrapbook::firstOrNew(['user_id' => $user_id]);

        $scrapbook->save();

        $scrapbook->projects()->attach($project_id);

        return true;

    } else {

        return false;

    }
}

As it stands, the controller function actually does what it is supposed to (adds a project to a scrapbook). But what it returns is causing the AJAX request to class as an error so I am unable to handle this correctly. I assume I am supposed to return some kind of response object but I don't know what this is or what it needs to include.

Upvotes: 2

Views: 7273

Answers (4)

Sunil
Sunil

Reputation: 1176

In Routes:

Route::get('/url', 'controller_name@controller_function');

Ajax:

$.ajax({
    method: 'GET',
    url: 'url',
    data: {},
    success: function( response ){
        console.log( response );
    },
    error: function( e ) {
        console.log(e);
    }
});

In response , send json:

return response()->json(['message' => 'successfull'],200);

Upvotes: 1

Akshay Kulkarni
Akshay Kulkarni

Reputation: 740

You can simply return an array containing whether it is success or it is failed.

$output_data = ['response' => true, 'message' => 'request is successful.' ];
$output_data = ['response' => false, 'message' => 'error message for user.' ];
return $output_data;

This will return control in success block of ajax. You can check there is the response is true or false and execute the code accordingly.

Upvotes: 2

The Alpha
The Alpha

Reputation: 146269

You may return a json response on success:

public function add( $user_id, $project_id )
{
    // Other code ...

    $isSuccess = false;

    if ($project->user_id != $user_id) {

        $scrapbook = Scrapbook::firstOrNew(['user_id' => $user_id]);

        if ($isSuccess = $scrapbook->save()) {
            // only attach it if successfully saved
            $scrapbook->projects()->attach($project_id);
        }

    }

    return response()->json([
        'success' => $isSuccess
    ]);
}

So in your ajax response you can check:

success: function( response ){
    console.log( response.success ); // true or false
}

Upvotes: 1

Mahdi Younesi
Mahdi Younesi

Reputation: 7509

You need to return a json response using json() fucntion

return response()->json(true);

or if want to send additional data back

return response()->json([
   'message' => 'successfull',
   'items' =>$insertedItems
],200);

or on fail

return response()->json(['error'=>'error text'],$statusCode)

Upvotes: 1

Related Questions