Using the Mail API with AJAX

Asked

Viewed 383 times

1

I’m practicing ajax using the post office API. I did it! But these 2 situations happen:

1- Gets stuck in the Else block, so if I put an invalid zip code after listing a valid one shows nothing, nor msg error that I put to appear, just nothing, only if you put a valid one again.

2- I do not know if it is the way of my rough validation or I have to put something else... that when it shows the data and I want to show another, it does not erase the existing and yes put below what was and so on.

Code:

// Início.
           $('form').on('submit', (event) =>{                 
                event.preventDefault();

                // Pegando o valor digitado do usuário.
                var cep = $('#cep').val();

                // Validação do cep.
                if(cep.length != 8){
                    $('p').css({color: "red"})
                    $('p').html("CEP não existe.");
                }else if(isNaN(cep)){
                    $('p').css({color: "red"});
                    $('p').html("CEP inválido.");
                }else {

                    // Criando uma URL.
                    var url = "https://viacep.com.br/ws/" + cep + "/json/";

                    $.ajax({

                        type: 'GET',                          
                        url: url,                            
                        dataType: "JSON",                                                         
                        success: (resp) =>{
                            for(var i in resp) {                                    
                                $('#div').append("<h4>"+resp[i]+"</h4>");
                            }
                        },
                        error: (resp) =>{
                                $('p').css({color: "black"})
                                $('p').html("Error: ".resp);                            
                        }                            
                    });

                }

            })

  • having nothing to do with your question, my end result would be something like https://jsbin.com/sayozuk/2/edit?html,js,output ... I hope to learn a little bit about :)

1 answer

1

As for your first doubt, in this validation block:

if(cep.length != 8){
    $('p').css({color: "red"})
    $('p').html("CEP não existe.");
}else if(isNaN(cep)){
    $('p').css({color: "red"});
    $('p').html("CEP inválido.");
}else {
  ....

You could remove the last Else, and quit Function if any validation fails, something as simple as that:

if(cep.length != 8){
    $('p').css({color: "red"})
    $('p').html("CEP não existe.");
    return;
if(isNaN(cep)){
    $('p').css({color: "red"});
    $('p').html("CEP inválido.");
    return;
}

As for the second problem, how are you using the append to add content to div, will always add to the end, need to clear the contents of div before starting, for example:

success: (resp) =>{
    $('#div').html("");  // aqui limpa o conteúdo antes de adicionar as dados retornados
    for(var i in resp) {                                    
        $('#div').append("<h4>"+resp[i]+"</h4>");
    }

Also, if you just want to show the content, it would be better to do it with a simple click on a button instead of a Ubmit, this is just a suggestion.

  • instead of $('#div').html("") you can use $('#div').empty()

  • Thank you very much, I managed to solve the second problem. Now regarding the first with the if/Else I discarded, put straight and preferred to work with the errors that come from http codes. But I’ve set in statusCode the possible HTTP errors, but it doesn’t fall in the block, errors only appear in the log console, such as 400, 404...

  • I understand, but anyway if you can validate the value before making the call is very recommendable, avoid making an ajax call that will give error, reduces unnecessary traffic... it may be that any time the service blocks the wrong requests followed and ends up blocking your application for a while, depending on what you send on the call can even enter a Blacklist, stay tuned with this ;)

Browser other questions tagged

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