Problem with jquery-ui autocomplete via Ajax/PHP

Asked

Viewed 577 times

6

Talk to the guys! I’m doing an application that recovers cities from a SOAP webservice, my application is already all ok, with queries, however I’m trying to implement now an autocomplete, and I’ve been having some difficulties with my "source" jquery-ui, the returned data is correct for the source to handle the information, but the autocomplete does not associate what I am searching for and displays the entire list of results. I tried to create a function to query the webservice and store the result in a variable, to use only var within the source, but it did not work to pass an external function within the source. follow me code to see if someone gives a help!

$(".j_destino").autocomplete({
    minLength: 2,
    source: function (request, response) {
        $.ajax({
            url: "_cdn/ajax/destino.php",
            dataType: "json",
            type: 'POST',
            data: {action: 'searchCity'},
            success: function (resposta) {
                response(resposta.dados);
                console.log(response);
            }
        });
    },
    focus: function (event, ui) {
        $(".j_destino").val(ui.item.city);
        return false;
    },
    select: function (event, ui) {
        $(".j_destino").val(ui.item.city);
        $(".j_CityId").val(ui.item.id);
        return false;
    }
}).autocomplete("instance")._renderItem = function (ul, item) {
    return $("<li>").append("<a>" + item.city + "</a>").appendTo(ul);
};

This would be the alternative version and more optimized to do this but I’m not hitting something.

    function carregaDados() {
        $.ajax({
            url: "_cdn/ajax/destino.php",
            dataType: "json",
            type: 'POST',
            data: {action: 'searchCity'},
            success: function (resposta) {
                response(resposta.dados);
            }
        });
    }

    $(".j_destino").autocomplete({
        minLength: 3,
        source: carregaDados(),
        focus: function (event, ui) {
            $(".j_destino").val(ui.item.city);
            return false;
        },
        select: function (event, ui) {
            $(".j_destino").val(ui.item.city);
            $(".j_CityId").val(ui.item.id);
            return false;
        }
    }).autocomplete("instance")._renderItem = function (ul, item) {
        return $("<li>").append("<a>" + item.city + "</a>").appendTo(ul);
    };

That would be my PHP

<?php
session_start();
$getPost = filter_input_array(INPUT_POST, FILTER_DEFAULT);
$setPost = array_map('strip_tags', $getPost);
$post = array_map('trim', $setPost);

$Action = $post['action'];
$jSon = [];
unset($post['action']);
//sleep(1);

if ($Action):
    require('../../_app/Config.inc.php');

    $jSon['dados'] = null;
endif;

switch ($Action):
    case 'searchCity':
        $cidades = new pegarCidade;
        $cidades->getListaDeCidades();
        if ($cidades->getResult()):
            foreach ($cidades->getResult() as $key):
                 $jSon['dados'][] = ['id' => $key->CityId, 'city' => $key->CityNamePT];
            endforeach;
        endif;
        break;   

    default:
        $jSon['error'] = "Erro ao selecionar a ação!";
endswitch;

echo json_encode($jSon);

  • It turns out you didn’t put the jquery library. Or at least not in the correct order.

1 answer

0

Hello,

the problem is that you don’t seem to be passing the term to be searched for php try something like:

$("#auto_id").autocomplete( {
    source: function(request,response) {

        $.ajax ( {
          url: "_cdn/ajax/destino.php",
          type:'POST',
          data: {term: request.term,action: 'searchCity'},
          dataType: "json",
          success: function(data) {
            //what goes here?
                 } 
    }) }
});

and then in php you get the term value typed in $_POST['term']

  • But then in php I have to do an if ==, other than LIKE sql, then the return would only come if you type the full term.

  • What is the source of this information ? The cities in this case come from a database ?

  • No, they come from the query of the Soap webservice, then I store in cache, in the case how I am in tests, I leave in the session.

  • Take a look in this example.

  • Or look at this another example.

Browser other questions tagged

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