Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jrdavidson's avatar

Destroy with json

Withy this destroy method I am trying to set up some defaults for my Ajax Json data to be sent back to my front end. I'm wanting to know how I can change the errors reported based on whether or not ithe user and profile record wasn't deleted. If the user wasn't even found I want to send a different message. If the process was a success then create change the status to a success and put a success message.

http://laravel.io/bin

0 likes
33 replies
bashy's avatar

Think you need to update the laravel bin link.

However, I use something like this

var jqxhr = $.post("URI", {
    foo_id : foo_id
}, function() {
     //
}).done(function() {
    var json_response = jQuery.parseJSON(jqxhr.responseText);

    if (json_response.error === true)
    {
        // error 
    }
    else if (json_response.success === true)
    {
        // success
    }
}).fail(function(response, status, xhr) {
     alert(xhr)
}).always(function() {
    btn.button('reset')
});
bashy's avatar

Ah from method side. Just do some checks to see if methods return true or false?

jrdavidson's avatar

Oh I didn't know the something like $user->delete() returns a Boolean.

anyday's avatar

It's very unclear what you're trying to accomplish.

If you use the model::findOrFail(?) function, you're going to end up throwing an exception (a 500 http status error), which is fine if that's what you're checking for in the ajax call, but you may want to simplify by just checking for NULL.

But you're also deleting the user profile after you've deleted the model. I'm assuming "profile" is an eloquent relation?

I would do something like:

$user = User::find($id);

if(NULL === $user) {
     $defaultJsonOutput['error'] = 'No User Exists';
     return Response::json($defaultJsonOutput);
}

if(TRUE !== $user->profile->delete()){
     $defaultJsonOutput['error'] = 'Could Not Delete Profile';
     return Response::json($defaultJsonOutput);
}

if(TRUE !== $user->delete()){
     $defaultJsonOutput['error'] = 'Could Not Delete User';
     return Response::json($defaultJsonOutput);
}
jrdavidson's avatar

That sounds good but with the profile and user can I do this as a transaction.

bestmomo's avatar

The delete method returns TRUE or ends with an error, it never sends back FALSE.

bestmomo's avatar

The test is useless, even with TRUE.

@xtremer360 sure you can do transaction, it's always a good idea.

anyday's avatar

Oh, does it throw an exception? Seems silly for a function to return true or throw an exception. Hm

bestmomo's avatar

@anyday hum... there is a return FALSE too, I must look at it better...

Edit : It returns true if the model exists and all is ok and it returns false if an event halts the process.

jrdavidson's avatar

As much as I liked all the answers. I have decided to go another route especially after watching the the lesson https://laracasts.com/lessons/javascript-conveniences. In this video Jeff talks about some great ways to do asynchronous form requests with ajax and forms. I started implemented this into my own application and hit a road block. In the video he uses the native confim box and I decided to use my modal instead. I'm trying to figure out how to expand on my code so that when it hits the data-confirm (submit). It will show the modal with a certain message I put into the form data attributes such as the remote-title or remote-message.

As of right now what happens is after I fill out the form and click Create it shows the default text for the modal and doesn't display the changes I wanted to apply. I'm also curious to know if the way I'm handling the code is correct because it does the POST request as soon as I click create which should only be applying when I click in the modal confirm button. I was just going by the video lesson so I'm not sure where I made my mistake.

<form method="POST" action="http://backstage.app/backstage/users" accept-charset="UTF-8" data-remote="data-remote" data-title="Creating New User" data-message="Are you sure you want to create this user as it will be saved and the only way to make changes is edditing after its saved to the database?" id="basicForm"><input name="_token" type="hidden" value="AhckfFbNnBme6yCZ5qb8QHOFi9GWaK0LK16d7KOa">
                <div class="panel panel-default">
    <div class="panel-heading">
        <h4 class="panel-title">Create User Form</h4>
    </div><!-- panel-heading -->
    <div class="panel-body">
        <div class="row">
            <div class="form-group ">
                <label for="first_name" class="col-sm-3 control-label">First Name</label>
                <div class="col-sm-9">
                    <input class="form-control" required="required" name="first_name" type="text" id="first_name">

                </div>
            </div><!-- form-group -->    
            <div class="form-group ">
                <label for="last_name" class="col-sm-3 control-label">Last Name</label>
                <div class="col-sm-9">
                    <input class="form-control" required="required" name="last_name" type="text" id="last_name">

                </div>
            </div><!-- form-group -->    
            <div class="form-group ">
                <label for="username" class="col-sm-3 control-label">Username</label>
                <div class="col-sm-9">
                    <input class="form-control" required="required" name="username" type="text" id="username">

                </div>
            </div><!-- form-group -->    
            <div class="form-group ">
                <label for="email_address" class="col-sm-3 control-label">E-Mail Address</label>
                <div class="col-sm-9">
                    <input class="form-control" required="required" name="email_address" type="text" id="email_address">

                </div>
            </div><!-- form-group -->
            <div class="form-group ">
                <label for="password" class="col-sm-3 control-label">Password</label>
                <div class="col-sm-9">
                    <input class="form-control width100p" required="required" name="password" type="password" value="" id="password">

                </div>
            </div><!-- form-group -->
            <div class="form-group ">
                <label for="password_confirmation" class="col-sm-3 control-label">Password Confirmation</label>
                <div class="col-sm-9">
                    <input class="form-control width100p" required="required" name="password_confirmation" type="password" value="" id="password_confirmation">

                </div>
            </div><!-- form-group -->    
            <div class="form-group ">
                <label for="role_id" class="col-sm-3 control-label">User Role</label>
                <div class="col-sm-9">
                    <select id="role_id" class="width100p" required="required" name="role_id"><option value="default">Please Select</option><option value="1">Basic User</option><option value="2">Editor</option><option value="3">Administrator</option><option value="4">Owner</option></select>

                </div>
            </div><!-- form-group -->
            <div class="form-group ">
                <label for="status_id" class="col-sm-3 control-label">User Status</label>
                <div class="col-sm-9">
                    <select id="status_id" class="width100p" required="required" name="status_id"><option value="default">Please Select</option><option value="1">Active</option><option value="2">Inactive</option><option value="3">Suspended</option><option value="4">Banned</option></select>

                </div>
            </div><!-- form-group -->    
        </div><!-- row -->
    </div><!-- panel-body -->
    <div class="panel-footer">
      <div class="row">
        <div class="col-sm-9 col-sm-offset-3">
            <input class="btn btn-primary mr5" data-confirm="data-confirm" type="submit" value="Create">
            <input class="btn btn-dark" type="reset" value="Reset">
            <a href="http://backstage.app/backstage/users" class="btn btn-info">Back To Users</a>
        </div>
      </div>
    </div><!-- panel-footer -->  
</div><!-- panel -->            </form>
        </div><!-- col-md-6 -->
    </div>
</div>


                </div>

            </div>

        </section>

        <!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                <h4 class="modal-title" id="myModalLabel">Delete Confirmation</h4>
            </div>
            <div class="modal-body">
                <p>This is the default text.</p>
            </div>
            <div class="modal-footer">
                <button type="button" id="myModalCancel" class="btn btn-default" data-dismiss="modal">No</button>
                <button type="button" id="myModalConfirm" class="btn btn-primary">Yes</button>
            </div>
        </div><!-- modal-content -->
    </div><!-- modal-dialog -->
</div><!-- modal -->        
(function () {
    $('form[data-remote]').on('submit', function(e) {
        var form = $(this);
        var method = form.find('input[name="_method"]').val() || 'POST';
        var url = form.prop('action');

        $.ajax({
            type: method,
            url: url,
            data: form.serialize(),
            success: function(response) {
                //var title = form.data('remote-title');
                //var message = form.data('remote-message');
                var className = 'growl-error';
                if (response.errors == 0) {
                    className: 'growl-success'
                }
                $.gritter.add({
                    title: title,
                    text: message,
                    class_name: className
                })
            }
        });

        e.preventDefault();

    });

    $('input[data-confirm], button[data-confirm]').on('click', function(e) {
        var input = $(this);

        input.prop('disabled', 'disabled');

        $("#myModal").modal('show', function() {
            var title = form.data('remote-title');
            var message = form.data('remote-message');
            $('.model-header h1').html(title);
            $('.model-body p').html(message);
        });

        input.removeAttr('disabled');
    });

})();
bashy's avatar

Would be easier with a JSFiddle or something similar, too much code for anyone to know what's doing on :P

jrdavidson's avatar

The problem is when the button is clicked it does the post request before it shows the modal. So I was trying to figure out how in Jeff's lesson he doesn't have his post request done until the user clicks yes on he jQuery confirm.

bashy's avatar

Listen for the click event on that then?

jrdavidson's avatar

Alright however can you exam to me so I understand the only difference is the confirm I did as a modal and works differently.

bashy's avatar

I used a bootstrap confirm plugin (not sure what you're using)

http://myclabs.github.io/jquery.confirm/

$.confirm({
    text: "Are you sure you want to do that?",
    confirm: function(button) {
       // Yes is clicked
    },
    cancel: function(button) {
        // No is clicked
        btn.button('reset')
    }
});
thepsion5's avatar

If you had visited the link, you would have seen that the plugin it designed specifically to work with bootstrap's modals. But your response seems like you dismissed it offhand and then didn't take the time to respond with a full sentence. Which tends to encourage similar responses when asking for people to spend their time an energy helping you solve a technical issue. ;)

jrdavidson's avatar

I apologize and in line at the DMV and for some reason it doesn't allow for that domain or something so I can't get to it right now. I was going to when I returned home. It was my mistake I should have said something in my previous reply.

jrdavidson's avatar

I just got home and looked over the github confirm and it looks great. I'm going to try and use this and see what I can come up with. Thank you bashy for your help.

jrdavidson's avatar

However I found in my template I purchased that having a js plugin for confirms isn't required and that it can be done with just html5 elements and attributes.

For example of the attributes:

<button class="btn btn-dark btn-sm mr5" data-target=".bs-example-modal-lg" data-toggle="modal">Large Modal</button>

I looked all through the rendered page and also the external javascript sheets and not at any point does the modal get called with javascript.

thepsion5's avatar

The data attributes are used by Twitter Bootstrap's javascript code to set up the triggers for showing or hiding the modal. So in the end it's still using javascript, you just don't have to write any yourself.

Looking at the code here: http://jsfiddle.net/cL6mvkcr/2/ you should be able to fix this by adding e.preventDefault(); at the top of your button's click function.

1 like
jrdavidson's avatar

Okay but I don't understand why in Jeff's video his form does NOT submit and loads his confirm and yet when I click mine it does send a post request before loading the modal when the code is the same.

Next

Please or to participate in this conversation.