Return ajax function with result of an sql search

Asked

Viewed 1,432 times

2

I am doing a section on my website, in which there is a field select. When I select something in that select, i want to conduct a BD search by returning the information about that item selected to use this information in other parts of the site.

I thought I’d do it using jquery and ajax. I can carry out the search, but I’m having trouble catching the return of the search.

Ajax:

 $('#sedes').on('change', function() {
            var idLoja = this.value;
            alert(idLoja);
            $.ajax({
                url: "carregarInfo.php",
                type: "POST",
                data: {
                    id: idLoja
                },
                cache: false,
                processData:true,
                success: function(data)
                {
                    alert(data);   
                }
            });
        });

PHP:

<?php
require_once('conexao.php');


$idLoja = $_POST['id'];

$sql = "SELECT * FROM lojas WHERE idLoja = '$idLoja'";

$result = $conexao->query($sql) OR trigger_error($conexao->error."[$sql]");
$s = mysqli_fetch_array($result);


echo $s;

How can I do it the right way?

Or is there a better way to do it?

Thank you.

  • Missing you report how this ajax will work, such as data in JSON, HTML or TEXT.

  • Does Alert appear? Does it give an error in the console? what var_dump($s);?

  • There is another, echo did not print an array without you inform which index, you have to handle the data output.

  • var_dump prints the found array. Success Alert gives an array to string conversion error.

  • Hi Romario, and what would be the right use?

  • Romário, so you don’t go to the cup again, huh!

  • Okay, so do it echo json_encode($r); and in AJAX together dataType :'json', in the configuration object. Works?

  • 1

    Exactly the way Sergio did it is the best option to use!

  • Thanks Sergio, it worked with JSON. I didn’t know him. It will help a lot!

Show 4 more comments

1 answer

3


json

On the return of PHP, place:

echo json_encode($s);

In the JS place:

$.ajax({
      url: "carregarInfo.php",
      type: "POST",
      dataType: 'json',

The important thing in the above JS code is the dataType: 'json'.

Make a console.log(data) and see what returns.

Just do data.nome_do_campo_na_tabela. That one nome_do_campo_na_tabela is the name of the field that comes from array converted into json in the PHP, which is the name of the field in the table.

  • 2

    Thank you very much, it worked right!

Browser other questions tagged

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