Return of PHP Query in Ajax

Asked

Viewed 1,316 times

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);

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


RETURN PHP.FILE

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

In AJAX is BLANK does not return me anything!

  • Try to give a: echo json_encode($url); in your AJAX file.

  • Getting like this? $. ajax({ type: 'post', date: {id = Prod}, dataType: 'json', url: 'listingGabattribs.php', Success: Function(url){ //$('. return'). html(url); //console.log(url); echo json_encode($url); } });

  • No, this would be inside the AJAX file you call, in case no listaGabaritosSelecionados.php.

  • Oh yes, thank you. But he continues to return nothing!

3 answers

1

The error was due to want to run the.php file inside another folder, fixed with the help of @Israel Merljak

1


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

$.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));
    }
});

Don’t forget to recover 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 way:

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>

Exit: {"testing":"return","json":"of","a":"script","php":"!!!!"}

  • Buddy, I’m testing with the ID right in the query, but thanks for the tip, the problem is in the AJAX bring me this return, it can not return me anything!

  • tried a echo json_encode($valor) ?

  • Yes I am trying with echo json_encode($url); and it does not return me!

  • 1

    Amigo.. it’s simple. you’ve tried giving a console.log() in the return ?? You’re trying to print a javascript object in html. will not be possible, try to do $(".retorno").html(JSON.stringify(url))

  • Buddy, as amazing as it sounds, it didn’t work!

  • I’ll post the code I tested in the answer for you to see..

  • and it doesn’t work yet! Nothing returns to me!

  • So do us a favor, run your php script and paste us the full result. one makes a echo "<pre>"; var_dump($url); echo "</pre>"; and glue what return to see.

  • This is the return directly in the.php <pre>array(2) { [0]=> string(14) "urlDoAquivoAI" [1]=> string(23) "http://www.teste.com.br" } </pre> But AJAX still returns nothing!

  • cola on your question please.. are you sure this return is correct? It does not seem to me a valid json (or php).

  • Answered there in question!

  • It makes no sense not to run it. You’re making a echo json_encode($url); at the end of the PHP script? Update the code in your question to the current version. Have you tried to copy my example and run?? See if it works.

  • Doing here by your example worked! I will now identify in mine which error!

  • Amazing how my files don’t work! Your script works!

Show 10 more comments

0

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

Browser other questions tagged

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