Use array type variable that returns the ajax function in PHP?

Asked

Viewed 216 times

-1

inserir a descrição da imagem aquiI have to pick up a variable type array of ajax and is returning correctly to the console.log(date); but I’m not sure how to use the return variable inside the index.php file.

Index.php

</!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css"> 
</head>
<body>
    <div>
    <?php
        $data='';
    ?>
    <label class="label">CNPJ</label>
    <input type="text" class="form-control" name="cnpj" value=""/>
    <button 
        type="button" 
        class="btn btn-success" 
        id="myBuscaCNPJ">Pesquisar
    </button>
    <?php
        var_dump($data);
    ?>
    </div>
    <script src="js/jquery-3.3.1.js"></script>
    <script src="js/bootstrap.js"></script>
    <script type="text/javascript">
        $("#myBuscaCNPJ").on('click', function(){
            $.ajax({
                type: "POST",
                url: "banco.php",
                dataType: 'json',
                data: { cnpj: $('input[name="cnpj"]').val() },
                success: function(data) { 
                    console.log(data)
                }
            })
        })                    
    </script>
</body>
</html>  

javascript

<script src="js/jquery-3.3.1.js"></script>
<script src="js/bootstrap.js"></script>
<script type="text/javascript">
    $("#myBuscaCNPJ").on('click', function(){
        $.ajax({
            type: "POST",
            url: "banco.php",
            dataType: 'json',
            data: { cnpj: $('input[name="cnpj"]').val() },
            success: function(data) { result(data) };
        }
    }                    
});
});
</script>

php bank.

<?php 
    $chave = $_POST['cnpj'];
    $db = mysqli_connect('localhost', 'root', '123456789', 'exemplo');
    $strQuery = 'select * from filiais where id = ' .$chave;
    $dados = mysqli_query($db, $strQuery);
    $dados_array = mysqli_fetch_array($dados);
    var_dump($dados_array);
    echo json_encode($dados_array);
?>
  • Where are you really in trouble? Get some error message?

  • the value that returns is null, and I have already checked...when reading the database the value returns correct. But it does not arrive at my index.php

  • 2

    Some things need to be better explained in the question: 1) In banco.php, only one echo will not make the response JSON; 2) In Javascript, when receiving the response, you call a function result that is not in the question; 3) The file index.php did not make sense and apparently you did not understand correctly the concepts of frontend and backend - I suggest reviewing. Extras: what does the browser console say? And the tab network? Is the request being made? What was the return?

  • I believe you have to give a $Row re-turn;

  • 1

    Do the following, exchange $_POST for $_GET and test your request in hand. Ex. banco.php? cnpj=12345678, this way you will see what the.php database is returning. Note: for the answer to be treated as json, you must return only the result of json_encode, comment the var_dump

  • Bank.php tested in hand and result ok! See picture! Post running on the console of ajax function after added json_encode. Removed var_dump...already and do not know how to work or send the result to index.php... How to work index.php???

  • 1

    When you take the var_dump and add the echo json_encode, you will make the call through $.ajax, if the url is right and the server responds something, the answer will reach your function Success. I prefer to use $.ajax({my config}). done(Function(data){} ).fail( Function(){} ), now this does not indicate that everything went well, just indicates that it was on the server and back, to indicate that everything went well I would put in the answer something like 'status' where 1 = ok , 0 = failure

  • the array is returning correctly, but I don’t know how to use it in index.php. Can you print the array variable inside the index.php? I’ll try to use it the way you posted it...

  • 1

    done(Function(data){ was on the server and returned }). fail(Function(){ failed to go on the server }), return structure {date:<response data>, status:<1=success, 0=wrong>} i.e., if the query der error vc returns {status:0} , if everything is ok returns {date:data_array, status:1} that answer will arrive on the done(Function(date)' date.status, date.date } ) Link

  • 1

    puts $.ajax({suacao}). done(Function(data)' Document.body.innerHTML= JSON.stringify( date) ; })

  • Icaro, this command worked perfectly and the data went to the screen. But I wanted something I could use like this: <input type="text" name="cnpj" value=dados_array['cnpj']/> <input type="text" name="name" value=dados_array['name']/> Is that right? Note that this was the purpose of the question from the beginning and I am not asking another question...just following to resolve my initial doubt! You can go to CHAT?

  • 1

    Not now, but what you want now is jquery, e.g. to create an input > minput=$('<input>'), apendar > $(Document.body). append( minput ); change properties > minput.prop( {name:'cnpj',value:'12345' });

  • ok. .Entendi. I will close the question because the main one has already been done. Thank you! I will test the jquery commands here...

Show 9 more comments

2 answers

1

If you are doing POST at least you have to get the variable

 $cnpj =htmlspecialchars($_POST["cnpj"]);
  • I used...this correct so far, but I don’t know how to use it in index.php

1

The expected output you probably want is a JSON?

 <?php 
 echo json_encode($dados_array);
 ?>
  • I used...this correct so far, but I don’t know how to use it in index.php Thanks, I’ve added a little bit for you!

  • 1

    return data, is a javascript array, example: data[0].id, data[0].nome as in php: $dados_array[0]['id']; $dados_array[0]['nome']

  • Got it! I managed to resolve this issue with the help of everyone here. But it was very well resolved. I hope it will help others!

Browser other questions tagged

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