I need to check if my JSON is empty to fetch url with parameter defined in the curl

1
function BuscaMarca(marca, modelo, anomodelo) {
    marca = $('#marca').val();
    tipo = $('#tipo').val();
    $.get("curl.php?tabela=BuscaMarca&marca=" + marca + "&tipo=" + tipo, function(data, status) {
        if (data == 0) {
            alert("Empty");
        } else {
            $('#marca').html(data);
            BuscaModelo(); //Busca o Modelo 
        }

    });
}

I need some way, make and type are empty, it has to be table = SearchByName & = = type = 0

    
asked by anonymous 27.10.2016 / 15:30

3 answers

1

You just need to validate the variables

tipo = $('#tipo').val();
if(tipo=="")tipo=0;
    
27.10.2016 / 15:42
1

Make a Ternary IF on receiving the value of the field, asking if the content of the value is greater than 0. If it is not, it is 0.

IF Ternary

VARIÁVEL = (CONDIÇÃO) ? VERDADEIRO : FALSO

Code

function BuscaMarca(marca, modelo, anomodelo) {

    marca = ($('#marca').val().length > 0) ? $('#marca').val() : 0;
    tipo  = ($('#tipo').val().length > 0) ? $('#tipo').val() : 0;

    $.get("curl.php?tabela=BuscaMarca&marca=" + marca + "&tipo=" + tipo, function(data, status) {
        if (data == 0) {
            alert("Empty");
        } else {
            $('#marca').html(data);
            BuscaModelo(); //Busca o Modelo 
        }

    });
}
    
27.10.2016 / 15:37
1

You can do an inline conditional to check if they are empty and assign the values accordingly, as follows:

marca = ( $('#marca').val() != '' ? $('#marca').val() : '' );

Note: It does a check of the tag value, if it is different from empty, it executes what comes after the ? which is the value itself, otherwise it executes after the : which is the value default that you specify.

That way the type would look like:

tipo = ( $('#tipo').val() != '' ? $('#tipo').val() : '0' );
    
27.10.2016 / 15:39