Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
Ajax gets only success response in Laravel

My ajax code always receives a success response even in case of error. I'm using Laravel 8.2.

Here is JavaScript

    $(".deleteRecord").click(function(){
    var id = $(this).data("id");
    var token = $("meta[name='csrf-token']").attr("content");
    if(confirm('Do you want to delete?')){
        $.ajax(
            {
                url: "operDel/"+id,
                type: 'post',
                cache: false,
                data: {
                    "id": id,
                    "method": 'post',
                    "_token": token,
                },
                dataType: "json",
                success: function() {
                    alert('Record is deleted'); // I getting only this alert
                },
                error: function() {
                    alert('You can not delete this record');
                }
            });
    }
});

Here is Route

Route::post('operDel/{id}', '\App\Http\Controllers\OperationController@destroy')->name('operDel')->middleware('auth');

Here is Contoller

    public function destroy($id)
{

    $user = User::find($id);
    if($user->type !== 0) {
            $user->delete();
            return response()->json([
                'success'=>"Record deleted."
            ]);
    }
    else{
        return response()->json([
            'error' => "You can not delete this"
        ]);
    }
}

The controller is running without error, it deleted record from DB when $user-> type! == 0. But I'm getting only the alert within the success function. How can I display response message to alert?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to send error response codes in order for AJAX to consider a response to have failed, for example:

public function destroy($id)
{

    $user = User::find($id);
    if($user->type !== 0) {
            $user->delete();
            return response()->json([
                'success'=>"Record deleted."
            ]);
    }
    else{
        return response()->json([
            'error' => "You can not delete this"
        ], 400); // 400 means bad request
    }
}

Sending a response code that's 400+ will make AJAX understand that there was an error.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!