1

I am trying to delete a user based on user input in a modal form, but I am unable to do that. There is no error message in the console. Since I have started learning very recently, I am unable to identify where I am doing wrong.

I am directly getting the error: part of the Ajax request.

Here is my code

Only the modal part of Blade

<button type="button" id="delete_user" class="btn btn-danger" data-toggle="modal" data-target="#deleteModal">Delete</button>

<div class="modal fade" id="deleteModal"  role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header ">
      
        <h5 class="modal-title text-danger text-center"  id="exampleModalLabel" >Are you sure you want to delete this user?</h5>
       
      </div>
      <div class="modal-body ">
        <strong class="text-info text-center ">Please Confirm your Details</strong>
        <form id="delete_user_form" method="POST">
          @csrf
          <div class="form-group">
             <input type="hidden" name="_token" id="d_csrf" value="{{Session::token()}}">
            <input type="hidden" class="form-control" id="d_id" name="d_id" value="{{Auth::user()->id}}">
            <label for="d_full_name" class="col-form-label">Full Name:</label>
            <input type="text" class="form-control" id="d_full_name" name="d_full_name">
          </div>
          <div class="form-group">
            <label for="d_password" class="col-form-label">Confirm Your Password:</label>
            <input type="password" class="form-control" name="d_password" id="d_password">
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="submit" class="btn btn-primary" id="final_delete">Delete User</button>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">
   $(document).ready(function(){
    $('#delete_user').click(function(e){
      e.preventDefault();
       // $("#deleteModal").modal('show');
      
         $('#final_delete').on('click', function(e) {
            e.preventDefault();
             $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });
       
            $.ajax({
               method:"POST",
               url:"delete_user",
               cache: false,
               processData:true,   //Required
               contentType: 'application/x-www-form-urlencoded',
               data:{
                      'd_token'             :    $("#csrf").val(),
                     'id' : $('#d_id').val(),
                     'd_full_name' : $('#d_full_name').val(),
                     'd_password' : $('#d_password').val(),

                },
                dataType :"JSON",
                success:function(){
                  swal({
                   title: "User deleted Successfully",
                   text: "You will now be logged out.Sorry to see you go!!",
                   icon: "warning",
                   buttons: true,
                  dangerMode: true,
                  });

                   
                },
                error:function(e){
                  swal({
                   title: "Oops! Some Error",
                   text: "Please try again later",
                   icon: "warning",
                   buttons: true,
                  dangerMode: true,
                  });
console.log(e);
                   

                },
            }); //ajax ends here

          }); //$("#final_delete").click ends
 ////$('#delete_user').click(function(e) ends

 });
  });
</script>

and controller

public function delete_user(Request $request){
   $d_id =  $request->id;
   $d_fname = $request->full_name;
   $d_password   =   $request->password;
   date_default_timezone_set("Asia/Kolkata"); 
   $d_time                 =   date("Y-m-d,H:i:s ");
$user_data  =    array(
        'id'  => $d_id,
         'full_name'     =>    $d_fname,
       'password'  =>   $d_password
    );
$act2= "DELETE";
if(Auth::attempt($user_data)){
     DB::select('CALL my_stored_procedures(?,?,?,?,?,?,?,?,?,?,?,?)', array($act2,$u_id,"","","","","",$$d_time, "","","",$d_time  ));
       return response()->json(
           [
               'success' => true,
               
           ]
       );
       Auth::logout();
       Session::flush();
       return redirect('login');
  }
  





} // delete_user ends

And view

Route::post('delete_user', 'userController@delete_user')->middleware('auth');

Here is the response obtained in the console (of the error: part of Ajax request)


dashboard:226 
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
abort: ƒ ( statusText )
always: ƒ ()
catch: ƒ ( fn )
done: ƒ ()
fail: ƒ ()
getAllResponseHeaders: ƒ ()
getResponseHeader: ƒ ( key )
overrideMimeType: ƒ ( type )
pipe: ƒ ( /* fnDone, fnFail, fnProgress */ )
progress: ƒ ()
promise: ƒ ( obj )
readyState: 4
responseText: ""
setRequestHeader: ƒ ( name, value )
state: ƒ ()
status: 200
statusCode: ƒ ( map )
statusText: "OK"
then: ƒ ( onFulfilled, onRejected, onProgress )
__proto__: Object

Any help is appreciated.

5
  • Check the response in chrome console. Commented Oct 9, 2020 at 10:56
  • @itachi There is no response. No error message in console of Chrome browser or anything Commented Oct 9, 2020 at 10:57
  • how you are providing the authorization bearer or auth token for middleware ? Commented Oct 9, 2020 at 11:07
  • @Al-Amin I don't understand what you are asking Commented Oct 9, 2020 at 11:13
  • @Skumar , you are using middleware in your route.Are you an authorized user to delete that user ? If you are authorized or logged in then how you are providing the authorization credentials ? Commented Oct 9, 2020 at 11:23

3 Answers 3

1

Copy this and paste it in your respective controller code

DB::select('CALL my_stored_procedures(?,?,?,?,?,?,?,?,?,?,?,?)', array($act2,$d_id,"","","","","",$d_time, "","","",$d_time  ));

You made a typo of $d_id instead of $u_id

Sign up to request clarification or add additional context in comments.

Comments

1

Ensure meta tag is present in the head section of your main blade file

Here - < meta name="csrf-token" content="{{ csrf_token() }}" />

url: "{{ url('/delete_user') }}",

Try your URL in this way, also after you have registered the route in routes/web.php, run the command php artisan optimize:clear . This command will clear all your cached files. Hard refresh your browser and check once again. You can use axios also. Laravel is now having in-built support for it.

Comments

0

Try this code.

<button type="button" id="delete_user" class="btn btn-danger" data-toggle="modal" data-target="#deleteModal">Delete</button>

<div class="modal fade" id="deleteModal"  role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header ">
      
        <h5 class="modal-title text-danger text-center"  id="exampleModalLabel" >Are you sure you want to delete this user?</h5>
       
      </div>
      <div class="modal-body ">
        <strong class="text-info text-center ">Please Confirm your Details</strong>
        <form id="delete_user_form" method="POST">
          @csrf
          <div class="form-group">
             <input type="hidden" name="_token" id="d_csrf" value="{{Session::token()}}">
            <input type="hidden" class="form-control" id="d_id" name="d_id" value="{{Auth::user()->id}}">
            <label for="d_full_name" class="col-form-label">Full Name:</label>
            <input type="text" class="form-control" id="d_full_name" name="d_full_name">
          </div>
          <div class="form-group">
            <label for="d_password" class="col-form-label">Confirm Your Password:</label>
            <input type="password" class="form-control" name="d_password" id="d_password">
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
        <button type="submit" class="btn btn-primary" id="final_delete">Delete User</button>
      </div>
    </div>
  </div>
</div>

<script type="text/javascript">
$(document).ready(function(){
      
        $('#final_delete').on('click', function(e) {
            e.preventDefault();
             $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
          });

          var get_data = $("#delete_user_form").serialize();   
       
          $.ajax({
             method:"POST",
             url:"delete_user",
             cache: false,
             processData:true,   //Required
             contentType: 'application/x-www-form-urlencoded',
             data : get_data,
              success:function(){
                swal({
                 title: "User deleted Successfully",
                 text: "You will now be logged out.Sorry to see you go!!",
                 icon: "warning",
                 buttons: true,
                dangerMode: true,
                });

                 
              },
              error:function(){
                swal({
                 title: "Oops! Some Error",
                 text: "Please try again later",
                 icon: "warning",
                 buttons: true,
                dangerMode: true,
                });
                 

              },
          });

        });
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.