Rosamunda Rosamunda - 27 days ago 7
Ajax Question

Why this form won't call the JS function? (trying to get an autocomplete form field calling a MySQL database with a PHP script and AJAX)

I'm trying to use the .autocomplete() function of jQuery UI with a list of usernames taken from a MySQL database (using a PHP script), but for some reason is not working. The console won't show me any errors.

The form have several items in it and it does work ok (the form is at the

editarPerfil.php
file, which gets processed by
guardarConfigPerfil.php
file).

But for some reason, I don't get anything from the JS file, which should be called when the content of the
userName
field is changed.

This is my HTML form:



<form method="POST" action ="guardarConfigPerfil.php">
<div class="form-group ui-widget">
<label for="userName">Username</label>
<input type="userName" class="form-control" value="<?php echo $userName; ?>" name="userName" id="userName" onchange="autocompletarUserNames();">
</div>


This is at my footer on that page:



<!-- jQuery y Bootstrap minificados -->
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="/js/formularios.js"></script>


This is my formularios.js file:



function autocompletarUserNames() {
$( "#userName" ).autocomplete({
source: '/perfil/autocompletarUsername.php'
});
};


This is my php file:



<?php
session_start();
include $_SERVER['DOCUMENT_ROOT'].'/private/conectar.php';

$conectar = new PDO('mysql:host='.HOST.'; dbname='.DATABASE.'; charset=utf8', USER, PASS);

//get search term
$user = $_GET['userName'];

$buscarUsuario = $conectar->prepare("
SELECT userName
FROM usuarios
WHERE userName
LIKE '%?%'
ORDER BY userName ASC
");
$buscarUsuario->bindParam(1, $user);
$buscarUsuario->execute();
$row = $buscarUsuario->fetchAll(PDO::FETCH_ASSOC);

foreach ($row as $key => $value) {
$data[] = $value['userName'];
}

//return json data
echo json_encode($data);
?>


Now, when I get into the form, and I click on the userName field and type... nothing happens. What am I doing wrong?

The folder tree is set up like this:

public_html/perfil/autocompletarUsername.php <--- the php script
public_html/perfil/editarPefil.php <--- the form
public_html/js/formularios.js <--- the js file

Answer

You should only ever have to call once:

$( "#userName" ).autocomplete({
    source: '/perfil/autocompletarUsername.php'
});

Most likely on page load, in the $(document).ready();

It looks like when you make a change to the text box, autocomplete is initiated again and again. Try removing the onChange and calling autocomplete like this:

$(document).ready(function() {
    $( "#userName" ).autocomplete({
        source: '/perfil/autocompletarUsername.php'
     });
});

Once. This is assuming your file path is correct, of course.

Comments