Return of the ajax function with result of a sql search

2

I'm making a section on my site, which has a select field. When I select something in this select , I want to perform a search on the DB, returning information about that selected item to use that information elsewhere in the site.

I thought about doing this using jquery and ajax . I can do the search, but I'm having trouble fetching the search return.

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 this the right way?

Or is there a better way to do this?

Thank you.

    
asked by anonymous 29.09.2015 / 21:04

1 answer

3

jSON

PHP return, put:

echo json_encode($s);

No JS put:

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

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

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

Just do data.nome_do_campo_na_tabela . This nome_do_campo_na_tabela is the field name that comes from the array converted to json in PHP , which is the field name in the table.

    
29.09.2015 / 21:26