Ajax does not return to view using find()

Asked

Viewed 43 times

1

Hello, I am creating an ajax but if I use find to return in the desired div it does not return

success: function (ret) {
            if (ret == "sucesso") {
                $(this).find(".msg-envio").html("<p class='msg-sucesso'>Orçamento enviado com sucesso!</p>");
            }
            else {
                $(this).find(".msg-envio").html("<p class='msg-erro'>Houve um erro ao enviar o orçamento.</p>");
            }
        }

1 answer

3


The this inside ajax is in another scope. You have to create a variable to store that reference because ajax assigns something else to this.

You put in a little code so I’ll give you an approximate example of your code:

// antes do ajax
var self = this; // <-- aqui guardas a referência
$.ajax({
    // etc
    success: function (ret) {
        if (ret == "sucesso") {
            $(self).find(".msg-envio").html("<p class='msg-sucesso'>Orçamento enviado com sucesso!</p>");
        }
        else {
            $(self).find(".msg-envio").html("<p class='msg-erro'>Houve um erro ao enviar o orçamento.</p>");
        }
    }
// etc...

There is however an option to force the use of this where ajax is called, in which case, instead of doing as I put it on top, add this to the object passed to ajax:

context: this,
  • 1

    It worked Sergio, I didn’t know this was neutral inside the ajax, Obg.

  • @Brendoll. great that worked. I joined another alternative now to complete.

  • Just to let you know. Reduce the search scope of find(), it is costly, for it sweeps through all GIFT in search of pouch. If you know where your .msg_envio, restrict the search. Ex: $('#divQueContemMsgEnvio').find('.msg_envio') will already reduce the scope of the search. Or change a find() by an id $('#id_msg_envio') is very performatic.

  • @Thiagolunardi well seen. By the way (Brendol L.) this element $(self).find(".msg-envio") should be cached, so you don’t have to call the selector every time.

Browser other questions tagged

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