Rosamunda Rosamunda - 1 year ago 47
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

file, which gets processed by

But for some reason, I don't get anything from the JS file, which should be called when the content of the
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();">

This is at my footer on that page:

<!-- jQuery y Bootstrap minificados -->
<script src=""></script>
<script src="//"></script>
<script src=""></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:

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 '%?%'
$buscarUsuario->bindParam(1, $user);
$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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download