Treat Exception in Jquery Post

Asked

Viewed 155 times

0

I have this function Javascript (Post Ajax) that when the post she’s passing theif (r != "") {. I needed to capture what was an exception and treat her out of the if.

JavaScript

function AsyncAlert() {
    $.post("MinhaUrl/AsyncMessage", {}, function (r) {
        if (r != "") {
            mensagemAlert(r);
        }
    });
}

C#

public JsonResult AsyncMessage()
{
    if(TemMensagemNovaAsync())
        return Json(_msgAsync);
    else
        return Json("");
}

Consider that I need to capture the exception if I haven’t been able to connect to the backend. In other words, the url server crashed, the url was not available

What better way for me to review this?

Observing: my language is C#.

  • Send request for what type of language? if you want to treat what for example, cites problems?

  • I am using C#

  • Bruno can be made a return with the exception you gave on the server, a suitable framework true or false, it is so nothing complicated, but at the same time I was in doubt because Mistakes can be several

  • But true or false comes in the "r" parameter in the case? I imagined something like the ajax post Success...

  • Bruno I can return anything by programming language, but, there is a doubt for example I can return like this r.success = true No problems quietly, but, it’s undefined as you want it to be returned. I can return the complete exection, I do not know if it is valid for your context... understood?

  • Oh yes... I understood what you meant. My concern is not in the backend, because there is already treated. The exception I refer to is for example failed to do the post in the URL.

  • Post your full javascript code and full backend please.

  • Even when he gives some exception he enters that function?

  • Virgilio, posted on.

  • jbueno, exactly what I want. Knowing q he could not enter the backend function.

  • So you want to treat the exceptions, Isn’t it? What I want to know is whether even when some Exception pops into the server side the client-side function is running. 'Cause if so, there’s something else wrong.

  • @jbueno, the server is already with the treatment not to burst exceptions. The only Exception that could pop up in this case is if the post could not access the URL. ie, some exception in the attempt to post.

Show 7 more comments

1 answer

1


In the documentation of $.post(), there is the .fail(). Use it to do something if an error occurs on the server.

A simple example would be this:

$.post("MinhaUrl/AsyncMessage", function() {
  console.log("sucesso");
}).done(function() {
  console.log("segundo sucesso");
}).fail(function() {
  console.log("error");
}).always(function() {
  console.log("terminou");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.