How to do something asynchronous with jQuery, search in Mysql with PHP?

Asked

Viewed 1,807 times

1

I’m having a lot of trouble with this part. I want to simply do a database search and move on to my main program, this without giving a refresh. I know how to do all part of PHP and Mysql, however the part of jQuery is no longer my area, I know the basics of JS.

Next: the research I want is SELECT questoes_resolvidas FROM dados_usuario WHERE id = id_usuario;. This I know how to do. But the big problem is to take this result and send it to my index php.. I don’t want to send the result inside a variable in the index php.. It can be a Javascript variable itself.

I’ve tried going through $_SESSION but you can’t, because I have to update the page to the $_SESSION take the updated values. I don’t want to refresh the page, but the variable with the response of the Mysql command will be updated every time I call the function try_it().

Help me, please. I’ve tried to learn this jQuery but I believe I need to delve into JS first, and I don’t have time for this right now.

  • Are you using any framework?

  • only bootstrap but use very little

  • On the server side is pure PHP then?

  • yes, I just want to return a string from a look at this other topic, it’s the same problem and I detailed there http://answall.com/questions/180156/como-buscar-valores-em-um-arquivo-php-com-jquery-ajax/180165#180165

3 answers

0

You can create a webservice to provide this data. Basically a file that will return only this data.

First create a file, ajax.php, for example. In it you make the query and write the result. To make it easy for you I recommend printing the data parsed in JSON.

Dps of this, in jquery vc uses the Ajax method $.ajax(options, callback)

Asynchronously it does a request in the URL q vc pass and when finished it calls the callback. When you fall into the callback you treat the data you received, or an eventual failure

  • Bro I’m sorry but the only thing I understood is ajax.php, there’s no way you can show me in code how to do not?

0

You will have to have a page to receive this ajax request.

I illustrated below, the connection to the bank is fictitious, just to illustrate.

ajax.php

// Apenas para exemplificar uma conexão com o DB
include("conexao_db.php");

$sql = <<<SQL
    SELECT *
    FROM minha_tabela
    WHERE minha_condicao = 1;
SQL;

$resultado = $db->query($sql);
$dados = $resultado->fetchAll();
// - - - - - - - - - - - - - - 

// Parte importante
header("content-type: application/json");
echo json_encode($dados);

There in your HTML you will make an AJAX request to the newly created page and include in the current page.

index.html

<h3>Meus dados</h3>

<ul id="minha_lista"></ul>

<script type="text/javascript">
    // Faz um requisição para a página "ajax.php", recebe os dados do servidor
    // e adiciona na lista vazia acima
    $.getJSON( "ajax.php", function( data ) {
        var items = [];

        $.each(data, function( key, val ) {
            items.push( "<li name='" + key + "'>" + val + "</li>" );
        });

        $('#minha_lista').html(items.join(''));
    });
</script>
  • Does not want to work, is returning NULL 5 times

0


After a long time (I couldn’t remember this question anymore) I discovered with some searches on Google. It’s very simple:

$.ajax({
    type: "GET",//Tipo da requisicao, pode ser GET, POST, etc...
    data: {dado1: "Dado 1",dado2: "Dado 2"},
    url: "url_do_arquivo_que_faz_as_coisas.php",
    beforeSend: function(){
        console.log("Isso executara antes da requisicao");
    }
    success: function(responses){
        console.log(responses);//Aqui são os dados vindos do PHP
    }
});

If we had something like this in PHP

echo $_GET['dado1'].' - '.$_GET['dado2'];

We would have the following on our console after making the AJAX request:

Dado 1 -Dado 2

I hope I’ve helped those in need the way I did at the time. Besides, you should put the JS code in a function pq so you call when you want and as many times as you want, the rest and just modify...

Browser other questions tagged

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