How to query via AJAX and store the data in a javascript variable?

Asked

Viewed 446 times

1

I have this code

<script>

$(window).load(function(){

 var source = [{
label: "Tom Smith",
value: "1234"
}, {
label: "Tommy Smith",
value: "12321"
}];


$("#descricao").autocomplete({
    source: source,
    minLength: 1, //quantidade de caracteres para começar a buscar
    select: function (event, ui) {
        //evento de quando você seleciona uma opção        
        $("#descricao").val(ui.item.label); //seto a descrição para aparecer para usuario no input text
        $("#id").val(ui.item.value); //seto o id para ir para seu backend :D
        event.preventDefault();
    }
});
});//]]> 
</script>

I would like the values of my variable var source were received via ajax, so I adapted it as follows:

<html><head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <meta name="robots" content="noindex, nofollow">
  <meta name="googlebot" content="noindex, nofollow">
  <script type="text/javascript" src="//code.jquery.com/jquery-1.6.2.js"></script>
  <link rel="stylesheet" type="text/css" href="/css/normalize.css">
  <link rel="stylesheet" type="text/css" href="/css/result-light.css">
  <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.14/jquery-ui.min.js"></script>
  <link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.14/themes/black-tie/jquery-ui.css">
  <title>jQueryUI 1.8.14 Autocomplete</title>
  <script type="text/javascript">//<![CDATA[

  function busca(x){

    var url = "autocomplete.php?q=" + x;

    $.ajax({
    type:"GET",
    url: url,
    dataType:'text',
     success : function(data)
         {
            var source =  data ;
       
         }
    });
}





$(window).load(function(){


$("#descricao").autocomplete({
    source: source,
    minLength: 1, //quantidade de caracteres para começar a buscar
    select: function (event, ui) {
        //evento de quando você seleciona uma opção        
        $("#descricao").val(ui.item.label); //seto a descrição para aparecer para usuario no input text
        $("#id").val(ui.item.value); //seto o id para ir para seu backend :D
        event.preventDefault();
    }
});
});//]]> 
</script>
</head>
<body>
  <input type="text" id="descricao" onkeyup="busca(this.value);" class="ui-autocomplete-input" autocomplete="off" role="textbox" aria-autocomplete="list" aria-haspopup="true">
<input type="text" name="idQueVaiParaSeuBackEnd" id="id">
  
  <script>
  // tell the embed parent frame the height of the content
  if (window.parent && window.parent.parent){
    window.parent.parent.postMessage(["resultsFrame", {
      height: document.body.getBoundingClientRect().height,
      slug: "None"
    }], "*")
  }
</script>

<div id="resultado"></div>



<ul class="ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all" role="listbox" aria-activedescendant="ui-active-menuitem" style="z-index: 1; top: 20px; left: 0px; display: none; width: 167px;"><li class="ui-menu-item" role="menuitem"><a class="ui-corner-all" tabindex="-1">Tom Smith</a></li><li class="ui-menu-item" role="menuitem"><a class="ui-corner-all" tabindex="-1">Tommy Smith</a></li></ul></body></html>

But then the values are not being interpreted by my code.

Below, follow the code of the file autocomplete.php. It generates the result in a format that should be interpreted by javascript

<?php 
if (!empty($_GET['q'])){
$link = new mysqli("localhost", "root", "minhasenha", "meudb");

$produto = $_GET['q'];

$produto =  '%'.$produto.'%';

$busca_produtos = $link->prepare("SELECT id, nome_com from cadastro where nome_com LIKE ? LIMIT 10");

$busca_produtos->bind_param("s", $produto);

$busca_produtos->bind_result($id, $nome_com);

$busca_produtos->execute();

$busca_produtos->store_result();

if($busca_produtos->num_rows() > 0){

	echo "[";

	while ($busca_produtos->fetch()) {
		echo "{ label: \"$nome_com\", value: \"$id\" },";

	} 

	echo "];";
	// Esta chave fecha o while ($busca_produtos->fetch()) { 

   } // Esta cahve fecha o if($busca_produtos->num_rows() > 0){

} // Esta chave fecha o if (!empty($_GET['q'])){
?>

The end result will be this: autocomplete

How do I receive the result via ajax and store in the variable?

1 answer

1

By the way Javascript works, the page executes all the code that is in it in order. The method you define as callback successful ajax request, however, only executes when server return occurs - after your server assembly autocomplete.

The solution is to assemble your autocomplete within a function, and perform that function within the callback of the ajax request.

Thus:

var montaAutocomplete = function (source) {
    $("#descricao").autocomplete({
        source: source,
        minLength: 1, //quantidade de caracteres para começar a buscar
        select: function (event, ui) {
            //evento de quando você seleciona uma opção        
            $("#descricao").val(ui.item.label);
            $("#id").val(ui.item.value);
            event.preventDefault();
        }
    });
}

And in the reposition:

$.ajax({
    type:"GET",
    url: url,
    dataType:'text',
    success : function(data) {
        montarAutocomplete(data);
    }
});
  • Renan, I did it this way: https://s4.postimg.org/v5la3tjv1/autocompl.png - But I still do not receive data. Did I ride the right way?

  • No... so you mount the autocomplete every time you change the text. The source only needs to be mounted once, as far as I understand from the autocomplete library.

  • I intend to make the data dynamic, that is, every time the user enters something, it performs a search in the table, not being necessary to load all the data at once. I still need to ride once?

  • Yes. When you mount the autocomplete it stores the URL and sends the requests to the server alone. You need to use a library called Bloodhound to allow this, take a look at the autocomplete documentation.

Browser other questions tagged

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