Laravel CMS | N-06 | Edit\Remove Categories using Ajax and Popups

Video Tutorial

During your Learning Journey, I suppose that you have seen a popup Hover above all the other page elements, lt say when you try to edit a post on social networks or adjusting settings, nowadays it is widely used on popular platforms and web services/apps

for ease of use also for nice UI/UX for the users, therefore, we are going to use a popup modal shows up when we try to Edit or Remove a Category, since we have already created the non-functional colored buttons last time, ready for integration.

So for using popup models, create a modal.blade.php under views/inc and add bootstrap popup modal HTML Code, here are a snippet for the Remove and Edit popups

Remove ×

`Delete! Are You Sure?```

CloseOK

Edit ×

New Name

`CloseOK```

you can copy paste the above code, or check here for the official docs.

Now you need to include the modal.blade.php in the main app.blade.php for using it later from JS.

Showing Popups

Now we need to trigger the popups (Show and Hide) by clicking the edit or remove category buttons, make sure to give each popup modal an ID for referencing it, also we need to add to the OK button in the footer area of the modal and attribute for checking if the button has been clicked or no, add data-js-type=”modal-submit” only for the remove Modal. For Now!

CODE HERE FOR ATTRIBUTES

Also Make Sure to add two attributes for our Category Buttons data-js=”open-remove” and data-js=”open-edit” each one correspond to it element’s function. for checking the click event on the buttons.

We need a JavaScript File for doing our Logic, So go ahead and create a main.js file under Resources/js, and make sure to require it on the app.js file on the same directory for telling laravel that we want to include the JS File to Compilation Process (The Same Process For the CSS SASS)

//app.js file Under resources/js 
...
main = require("./main/main.js"); ///< we also put main.js file under a folder called main 
...

So For Triggering the popup on the remove button click

open the JS File and using JQuery Selector Magic we grab the element and we bind click event for the button and we open up the modal on that, this piece of code should demonstrate HOW?

$(function() { ///< On Document Ready!

  $('data-js=open-remove').on('click', function(e) {
       $('#removeModal').modal(); ///< Modal is a bootstrap func for Showing the Popup
  });

  //We Also do the same thing for the Edit Modal, only changing the event button and the modal 
  $('data-js=open-edit').on('click', function(e) {
       $('#editModal').modal(); ///< Modal is a bootstrap func for Showing the Popup
  });
});
//NOTICE: You have to Know the Basic Things about JQUERY First!

You can click on the remove button under the category and you should see a Nice Popup Slowly land from the top of your page.

As you may notice, we also did the same event binding for the Edit Button.

Submitting With AJAX

So AJAX will allow us to call the backend (Server Script) and Talk to the Database without reloading the hole page, only a portion of it. You still can use a normal Form Submitting Method, but I think it is time to try something a bit more powerful.

in the main JS File, we have to check the submit of the form, or for the click of the OK button on our popup modal, For this case we are going to use Different Methods for getting the click event on the Remove and Edit Popups

For the Remove, we are going to check the click event of the OK Button.

For the Edit, we are going to check against the Form Submit event, You may not have noticed that but there is a Form under our footer are on the Edit popup, which is Containing the Close and OK buttons, check the Modal Code Snippets above.

Removing the Category

we check the popup submit button click

$('[data-js-type=modal-submit]').on('click', function(e) {
 //AJAX Call Goes here 
});

Now with Ajax, we are going to send the Category id, that we can grab from the firstly clicked button on the category, under the span element, check the last tutorial for more info.

$('[data-js-type=modal-submit]').on('click', function(e) {
    $.ajax({
        url: "deleteCategory",
        method: "POST",
        dataType: "json",
        data: { id: $("[data-js=open-remove]").find('span').attr('id') },
        success: function(result) {
            console.log("Success : ", result);
        },
        error: function(error) {
            console.log("AJAX ERROR: ", error);
        }
    });

});

It may seem a bit frustrating, but actually, it is very simple, let us walk through this piece of code.

First, we use Jquery AJAX Method, and we pass in an object, the URL pointing to /deleteCategory route that you need to set it up on the web.php file routing the post request to the controller on a method we are going to create called removeCategory()

the we specify the request method (POST) datatype: the return type gonna be JSON and of course the data we wanna pass in to The PHP Script under the data attribute we create an Object which is actually just getting the data from our Remove Category Button specifically from the span element, in order to find the category on the database.

the Success gonna be triggered by a Successful Request and Response, and the Error triggered by an Error (Most Likely HTTP ERROR)

On the Success, as you can we are checking for a Success or Error Respons from the Result which is Returned back by the Server (The PHP Script) and here we are doing our custom checking (for e.x: the ID is invalid, we return an Error Message), and we optionally the page for changes to take effect.

//So under the Success Function we check for our Success Message 
if (result.Success) {
    //Reload the Page 
    document.location.reload(true);
} else if (result.Error) {
    console.log('Error From the Sever ', result.Error);
}

Now we need to rout the deleteCategory URL to the method on our Category Controller

Route::post('/deleteCategory', 'CategoryController@removeCategory')->name('category.delete');

Then we delete the Category from the DataBase.

public function removeCategory(Request $request) {
     //Find the Category 
     $category = Category::findOrFail($request->id);

     //Delete the Category 
     $category->delete();

     //Session Massage 
     session()->flash('Success', 'Category Named ' . $category->name . ' Removed Successuflly');

     return json_encode(['Success' => 'Category Named ' . $category->name . ' Removed 
     Successuflly']);
}

as Simple as That, Trying to remove a category, should work for you without problems.

Now For Editing the Category, it is going to be the same process as removing, the only thing we need to change is Server Side Handling the Edit Request and the Form Submit

So the Ajax Call Would be

$('[data-js=open-edit]').on('click', function(e) {

    console.log('Clicked');
    $("#editModal").modal();
    //Opening the Modal 

});


$("#editForm").submit(function(e) {

    $.ajax({
        url: "/editCategory",
        method: "POST",
        dataType: "json",
        data: {
            id: $("[data-js=open-remove]").find("span").attr("id"),
            name: $('[data-js-type=editedText]').val()
        },
        success: function(result) {
            console.log("Success : ", result);
        },
        error: function(error) {
            console.log('AJAX ERROR: ', error);
        }
    });

    //Prevent Form Submitting
    e.preventDefault();
});

Notice: for the Edit we are sending the new name of the category alongside the Category ID.

Also Optionally you can reload on Success

if (result.Success) {
    //Reload the Page 
    document.location.reload(true);
} else if (result.Error) {
    console.log('Error From the Sever ', result.Error);
}

And You need to handle the Edit Request on the Server Side

public function editCategory(Request $request) {
    //Find Category 
    $category = Category::findOrFail($request->id);

    //Change the Name
    $category->name = $request->name;

    //Updating Category 
    $category->update();

    session()->flash('Success', 'Category Name changed Successfully to : ' . $category->name);

    return json_encode(['Success' => 'Category Name changed Successfully to : ' . $category->name]);
}

Now Open the Edit Popup and Enter a new Name, the process should go successfully with Page Reload.

So this was a quietly long Tutorial, if you still feeling a bit confused about AJAX Requests and Server Side Handling, you can watch the Video Tutorial Above for More Clarification.

What is Next

That was all of the Ajax and Category managing, In the Next Tutorial, we will cover Post Adding and a simple blog for fetching and showing our posts.

No Comments Yet