Managing failure function in AJAX: A comprehensive guide

I've been trying to manage the failure function in AJAX to display specific messages to users. Despite attempting various solutions, I have struggled to control the failure function. Here is my code:

<p id="Likes" class="alert-danger" style="display:none"></p>
<button title="Like" id="Like" data-id="@Model.Book.Book_id" class="like-toggle btn btn-group-sm red fa fa-2x" style="float:initial">❤ @Model.Book.Likes_Count</button>

$('.like-toggle').click(function () {
        var myId = $(this).data('id');

        $.ajax({
            type: "GET",
            url: '@Url.Action("Like", "Book")?Book_id=' + myId,
            success: function (response) {
                document.getElementById("Like").innerHTML = response;
            },
            failure: function (response) {

                $('#Likes').html(response).fadeIn('slow');
                $('#Likes').delay(8000).fadeOut('slow');
            }
        });
    });

Additionally, here is the controller code:

[HttpGet]
        public ActionResult Like(int? Book_id)
        {
            int state = 0;
            if (User.Identity.IsAuthenticated)
            {
                var x = User.Identity.GetUserId();
                var CheckIfExist = db.Likes.Where(p => p.Book_Id == Book_id && p.User_Id == x.ToString()).FirstOrDefault();
                if (CheckIfExist != null)
                {
                    return Content("You Liked This Book Before !");

                }
                else
                {
                    if (x != null)
                    {
                        var article = db.Books.Find(Book_id);
                        if (article != null)
                        {
                            article.Likes_Count += 1;
                            state = db.SaveChanges();
                            if (state == 1)
                            {
                                Like likes = new Like
                                {
                                    Book_Id = article.Book_id,
                                    User_Id = x
                                };
                                db.Likes.Add(likes);
                                state = db.SaveChanges();
                                if (state == 1)
                                {
                                    return Content("💗 " + article.Likes_Count.ToString());
                                }
                                else
                                {
                                    return Content("Failed To Save Your Like To DataBase !");

                                }
                            }

                            else
                            {
                                return Content("Failed To Save Your Like To DataBase !");

                            }

                        }
                        else
                        {
                            return Content("Book Does Not Exists In DataBase !");

                        }
                    }
                }


            }


            return Content("Only Registered Members Can Use Our Like System , Please Register To Be Able To Use Our Like System !");
        }

While my code appears to be functioning correctly during testing, it consistently returns values to the success function only. According to my code, any message besides updating the like count should be displayed in:

<p class="Likes"></p>

How can I determine which content should be returned to either the failure or success?

Answer №1

I came up with a solution by following these steps:

$('.like-toggle').click(function () {
    var myId = $(this).data('id');

    $.ajax({
        type: "GET",
        url: '@Url.Action("Like", "Book")?Book_id=' + myId,
        success: function(resp) {
            if(resp.success) {
                document.getElementById("Like").innerHTML = resp.responseText;
            } else {
                $('#myElem').html(resp).fadeIn('slow');
                $('#myElem').delay(8000).fadeOut('slow');
            }


        },



    });
});

And in the C# controller :

 return Json(new { success = true, responseText = value.ToString() }, JsonRequestBehavior.AllowGet);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JQuery - automatic redirection following a successful get request

Can a user be redirected when a get request is made? Take a look at this code snippet: $('.createNewPost').on('click', function(e) { e.preventDefault(); var notLoggedIn = false; $.get($(this).attr('href'), func ...

Is it permissible to make alterations to npm modules for node.js and then share them publicly?

I have made modifications to a module called scribe.js that I use in my own module, which is published on npm. Instead of using the original module as a dependency for my module, I would like to include my modified version. I am unsure about the legal impl ...

Ways to update modal content upon clicking a button

I have a scenario where I need to display 2 modals (box1 and box2) in my code with box2 appearing on top of box1. Each modal has its own button, and I want to make sure that box1 appears first. Then, when the user clicks the button in box1, it transitions ...

Tips for creating a loading page that displays while your website loads in the background

Is there a way to display a loading animation or image while my website is loading in the background? I've noticed that it takes about a minute for my website to fully load. I attempted to use <meta http-equiv="refresh" content="1000 ...

How can the session user object be modified after logging in?

I've encountered a strange issue and I'm puzzled about its origin. In my Next.js app, I make use of the next-auth library to implement the authentication system. Initially, everything seems fine - I can successfully sign in by verifying the cred ...

Declining the request to incorporate an external website into my web platform

While checking the console errors in Google Chrome, I encountered the following error message: The page 'https://website.com' was blocked from framing because a higher-level ancestor violates the Content Security Policy directive: "frame-an ...

dojo combobox with data loaded dynamically from JSON

I am facing an issue with populating a Combobox dynamically using a jsonRest from a cross-origin request. While I have managed to do it statically (if that's the correct term), I am struggling to implement it for multiple cases. This is just a small ...

Creating a realistic typewriter effect by incorporating Code Block as the input

I am looking to add a special touch to my website by showcasing a code segment with the Typewriter effect. I want this code block not only displayed but also "typed" out when the page loads. Unfortunately, I have been unable to find a suitable solution s ...

Submitting multiple forms using AJAX and PHP

I am currently trying to send the form data to another page for processing, but I am not receiving any data. Below are the forms in question: The default form is the login form for requesting a username and password, with only one submit button. ...

The Google Drive API in Node.js is notifying the deletion of files

I encountered an issue with the Google Drive API in my application. Even after deleting files from Google Drive, the listfiles function still returns those deleted files. Is there a solution to prevent this from happening? Below is the function of my API: ...

Check for length validation including spaces in JavaScript

My code includes a functionality that calculates the length of characters in a text area using both JSP and JavaScript: <textarea class="textAreaLarge" id="citation" rows="20" cols="180" name="citation" ...

Create a new object in Three.js every x seconds and continuously move each object forward in the Z-axis direction

I am currently developing a Three.js endless runner game where the player controls a character dodging cars on a moving road. At this early stage of development, my main challenge is to make the hero character appear to be moving forward while creating the ...

Addressing an error of "call stack full" in nextjs

I am currently working on a project in nextjs where I need my billboard to continuously scroll to show different information. The Nextjs debugger keeps showing me an error message that says 'call stack full'. How can I resolve this issue? con ...

Modify various entities with a singular PUT request (or POST)

I am currently developing a website that offers clients the ability to input tabular data (merchants) into a grid. Each entry has a unique identifier. I am interested in implementing batch updates using my Web API controller, rather than processing individ ...

Revamp a dynamically generated class using ajax

I am currently developing an email-based application using PHP and the CodeIgniter framework. My goal is to change the status of unread messages to read when they are clicked on, utilizing two different classes: read0 and read1. While I can view the messag ...

Issues with uploading files in NodeJs using express-fileupload are causing errors

I created a REST API in NodeJs for File Upload which is functioning correctly, however I am facing an issue. When I upload more than 2 images, only 2 or 3 get uploaded and sometimes one gets corrupted. I suspect that the loop is running too fast causing th ...

Having trouble with jQuery validation: Seeking clarification on the error

I have implemented some validations on a basic login page and added jQuery validation upon button click. However, the code is not functioning as expected. I have checked the console for errors but none were displayed. Here is the code for your review: ...

Finding and removing an element using Jquery

$.ajax({ type: "GET", url: "ajax/getLinks.php?url=" + thisArticleUrl }).done(function (data) { var extractedContent = $(data).find("#content > div > div.entry.clearfix"); extractedContent.find("#content > di ...

Initiate File Download using onclick event with Ext.Ajax.request

I'm attempting to initiate a file download by clicking on an anchor link with an onClick event: <a href="#download" onClick="downloadFile('@(elem.Attachment)')">@(elem.Attachment.Split('/').Last())</a> The variable el ...

Pair a specific portion of text with another string

I'm having trouble finding a substring within a string. The substring and the string are as follows: var str="My name is foo.I have bag(s)" var substr="I have bag(s)" When I use str.match(substr), it returns null, probably because the match() funct ...