Return data via Ajax

Asked

Viewed 268 times

0

Good morning everyone... I need a help... I need to return success or error values via ajax. But it is not returning anything. Follow the codes:

HTML

<div class="form-group col-md-4 col-xs-12">
    <input type="text" class="form-control input-lg" id="cep" name="ceps" placeholder="_____-___">
</div>
<button type="button" class="btn btn-warning botao" id="buscar">Calcular</button>
<div id="resultad"></div>

JS

$('#buscar').click(function(){
        $.ajax({                
            type:'POST',
            url:'/inc-busca-cep.php',
            dataType: 'html',
            data:{
                cep: $('cep').val()
            },              
            success: function(data){
                if (data){
                     $('#resultad').html('<span class="text-danger">Não entregamos neste cep</span>');
               } else {
                     $('#resultad').html('<span class="text-danger">Entregamos neste cep. Frete Grátis!</span>');
               }
            },

        });

        return false;
    });

PHP

$pdo = db_connect();
$cep = isset($_POST['cep']) ? $_POST['cep'] : null;
function limpa($valor){ $valor = trim($valor); $valor = str_replace("-", "", $valor); return $valor;}

$cepLimpo = limpa($cep);

$stmt = $pdo->prepare("SELECT * FROM ceps WHERE :a BETWEEN cep_de AND cep_ate");                                    
$stmt->bindParam(':a', $cepLimpo);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_OBJ);

if($result):
  echo "ok";
else:
  echo "erro";
endif;
  • Because there must be a syntax error in JS and you didn’t see it. Review your condition inside the callback success; there is a if which does not, in fact, have a.

  • I understood, but I don’t know how to do :( I’m learning ajax yet.... I only know how to use if in php

  • This is Javascript syntax, has no relation to AJAX and the syntax is the same as PHP. If you don’t know this yet, I recommend that you study at least the basics of Javascript before trying to do something more advanced: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else

  • @Andersoncarloswoss now understood what you meant... to do the same thing I did in if in PHP...

  • @Andersoncarloswoss made the adjustment in JS IF, but even so does not return me anything...

2 answers

1

Modify your Success function, before the conditionals put this:

    console.warn('retorno:', data);

Then open the browser console on the "console" tab and post a print of the result here...

  • 1

    I was able to return the ok or error... but how do I make an if in Ajax? Success: Function(data) { if ("ok"){ $('#resultad'). html('<span class="text-Danger">We do not deliver in this cep</span>'); } Else { $('#resultad'). html('<span class="text-Danger">Delivered in this zip. Free Shipping!</span>'); } console.log('Success!', date); }, error: Function(e) ː console.log('Error!', e); }

  • See, notice that you get the value due in the "date" attribute, so you have to make the conditional by checking the value of this attribute!

  • If you do this: if (data) { // does something } The conditional will check boolean, that is, if the returned data is 0, Undefined, null, false or empty string("") the result will be FALSE and the IF will not be executed by passing to the ELSE.

  • 1

    You can leave the ajax code the way it was at the beginning, but you will have to answer a boolean value in the server’s ECHO... Example: echo 1(if it’s all right) and echo 0(if it’s wrong). But since your server returns the "ok" and "error" strings as a response, then you should make the conditional as follows: if (date === "ok") { // success } Else { // failure(if it is anything other than "ok") }

  • mto obg worked right... and obg to everyone for help

0

Apparently the ajax request is not wrong. There must be some error in your php script I did a simulation here with a similar code and it worked. Make sure you added jquery and javascript to your html page correctly at the end of the file:

Below an example that worked

HTML:

    <div class="form-group col-md-4 col-xs-12">
        <input type="text" class="form-control input-lg" id="cep" name="ceps" placeholder="_____-___">
    </div>
    <button type="button" class="btn btn-warning botao" id="buscar">Calcular</button>
    <div id="resultad"></div>

   <!-- Adiciona JQUERY e script js para requisição ajax -->
    <script
    src="https://code.jquery.com/jquery-3.4.0.min.js"
    integrity="sha256-BJeo0qm959uMBGb65z40ejJYGSgR7REI4+CW1fNKwOg="
    crossorigin="anonymous"></script>
    <script src="js/main2.js"></script>

Javascript

        $('#buscar').click(function() {
        $.ajax({
            type: 'POST',
            url: '/post2.php',
            dataType: 'html',
            data: {
                cep: $('cep').val()
            },
            success: function(data) {
                if (data) {
                    $('#resultad').html('<span class="text-danger">Não entregamos neste cep</span>');
                } else {
                    $('#resultad').html('<span class="text-danger">Entregamos neste cep. Frete Grátis!</span>');
                }
            },


        });

        return false;
    });

PHP (Simplified presented only one echo to simulate your code)

    <?php 

echo "ok";
  • If in doubt, debug your console script.log(date)

  • Where do I put this console.log(date)

Browser other questions tagged

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