Ajax PHP Query Return

0

How do I get the PHP query values in AJAX?

AJAX

$.ajax({
   type: 'post',
   dataType: 'json',
   url: 'listaGabaritosSelecionados.php',
   success: function(url){
     $('.retorno').html(url);
   }
 });

PHP

$mysqli = new mysqli("localhost", "root", "", "site"); 
$idProduto = 42;
$query = "SELECT * FROM produto where produto_id = '$idProduto'";
$consulta = $mysqli->query($query);

while($row = $consulta->fetch_assoc()){

    $item = $row['item'];
    $ids = explode(',', $item);
    foreach ($ids as $valores) {

        $selecionaGabaritos = "SELECT * FROM gabaritos where id = '$valores' ";
        $banco = $mysqli->query($selecionaGabaritos);
        while ($resultado = $banco->fetch_assoc()) {
            $url[] = utf8_encode($resultado['url']);
        }
    }
}


json_encode($url);

I want to be sent a product ID for PHP, it does a query in the database in 2 tables, if I execute only the PHP file it runs, the problem is in AJAX for the return!

RETURN ARCHIVE.php

<pre>array(2) {
  [0]=>
  string(14) "urlDoArquivoAI"
  [1]=>
  string(23) "http://www.teste.com.br"
}
</pre>

In AJAX it stays in WHITE does not return anything to me!

    
asked by anonymous 11.09.2018 / 13:12

3 answers

1

Friend, you can send the (id) parameter directly through the ajax script. using the "date" option.

$.ajax({
    url: "listaGabaritosSelecionados.php",
    method: "POST",
    data: { id : seuIdAqui }, //{[nome_do_parametro_post]: [valor_do_parametro]}
    dataType: "json",
    success: function(data) {
        // Transforma json em string pra renderizar no html
        $(".retorno").html(JSON.stringify(data));
    }
});

Do not forget to retrieve this value in the PHP script using $_POST

A good tip is to read the documentation: jQuery.ajax () .

To return the value of the PHP script you can do this:

echo json_encode($valor_retorno)

Example code (tested)

PHP:
<?php

echo json_encode([
    "testando" => "retorno",
    "json" => "de",
    "um" => "script",
    "php" => "!!!!"
]);
Javascript:
<div id="here"></div>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous"></script>


<script>
    $(document).ready(function () {
        $.ajax({
            url: "rest.php",
            method: "POST",
            dataType: "json",
            success: function(data) {
               $("#here").html(JSON.stringify(data)); 
            }
        });
    });
</script>
  

Output:   {"testing": "return", "json": "of", "one": "script", "php": "!!!!"}

    
11.09.2018 / 13:20
0

On the last line of your file .php it replaces json_encode($url); with print_r($url) and checks the result. Because you are not giving any instructions to PHP to return the query data.

    
11.09.2018 / 13:31
0

The error was occurring due to wanting to execute the .php file inside another folder, solved with the help of @Israel Merljak

    
11.09.2018 / 14:44