lundi 29 mai 2017

delete a user post using ajax and js in laravel 5.4

I'm new to Laravel. I am trying to create a common social network, Now i want to delete a user's post, After hitting the form it loads the ajax but can not delete the data. Here I gave my code. /My ajax code is:/

`$("#_global_modal").delegate('#modal_form_delete', 'submit', 
 function(event) 
 {

    // To stop a form default behaviour
    event.preventDefault();

    $.ajax({ 
       url: $(this).attr('action'),               
       type: $(this).attr('method'), 
       dataType: 'json',
       data: $(this).serialize(),
   })
    .done(function(response){
        if(response.delete == "success"){
            window.location.href = response.redirect_route
        }else{
            console.log(response);
        }
    })
    .fail(function(){
        console.log("error");
    })
    .always(function(){
        console.log("complete");
    });

});`

/*Route:*/
`Route::post('delete','crude@delete')->name('delete');`


/*
    `route_user_post        =   "";
    route_delete_post   =   "";`
*/

 /*My controller part:*/

 `public function delete(Request $request)

 {
    if($request->ajax()){
       $user = Auth::user();
       $user->post()->delete(['post' => $request->post]);

       return response()->json([
                'delete'            =>  'success',
                'redirect_route'    =>  route('profile')
            ]);

    }else{
        return response()->json([
            'delete'            =>  'ERROR',
            'ERROR_MSG'    =>  'ERROR MSG'
        ]);
        dd("Sorry you have to send your form information by using ajax 
      request");
    }
 }`

 /*So how can I solve this problem?*/



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire