0

I've created a jQuery autocomplete with a set of predefined values.

$(function() {
    var foo = [
        "bar",
        "baz"
    ];
    $( "#foo-teszt" ).autocomplete({ source: foo });
});

What I would like to do, is that if the user changes the country, the names are changed in the foo. Initially it works, but when I use an AJAX call to change the variables. However, even after that, the variable remains the same. (I guess because the function does not look at the variable each time, but loads only once and reuses the foo the state it was the first time it was called.)

So I tried to invoke both the foo and the foo-teszt autocomplete in hope it will reload the contents of foo. I tried it with

$( function() {
    var foo = [
        "bar",
        "baz"
    ];
    $( "#foo-teszt" ).autocomplete({ source: foo });
})();

And giving the function a name and calling it with the country selects onChange, but neither of them worked, I still got the initial values.

I'm looking for this:

User selects a country from a select.

It's onchange makes an AJAX call, which returns the list of available cities in that country.

And the input field gets to load a new autocomplete with the returned AJAX values. (This is the part not working. The HTML source code script changes to the correct form, but the autocomplete is not loaded with the new variables.)

Dynamically changing javascript variable

I also tried this, while it was still running initially, after the AJAX call I still not call it with the onchange, nor within the AJAX itself.

AJAX is a jQuery like this.

$.ajax({ //jadajada
          url: "url",
          type: "post", //send it through get method
          data: {
            method: "baz",
            foo: bar
          },
          success: function(response) {
              document.getElementById("bal").innerHTML = response;
          },                                                              
          error: function(xhr) {
            //Do Something to handle error
          }
        });

3 Answers 3

1

You can check the autocomplete documentation API, you ll find the way to change the datasource dynamically :

https://api.jqueryui.com/autocomplete/#option-source

$( ".selector" ).autocomplete( "option", "source", [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby" ] );

for your case, initialize the autocomplete and then do a request that will return the new set of options :

$( function() {
   var foo = [
     "bar",
     "baz"
   ];
   $( "#foo-teszt" ).autocomplete({
     source: foo
   });
});

something like this :

$.ajax({ //jadajada
url: "url",
type: "post", //send it through get method
data: {
  method: "baz",
  foo: bar
},
success: function(myNewSource) {        
    $("#foo-teszt").autocomplete('option', 'source', myNewSource)
}                                                                  
});

EDIT : Add working example

$(function() {
  var json_data = JSON.stringify(["zz", "zzz", "sdf"]);


  var availableTags = [
    "ab",
    "abc",
    "ac"
  ];
  $("#tags").autocomplete({
    source: availableTags,
    search: null
  });


  $("#btn").on("click", function(e) {
    $.ajax({
      type: "POST",
      url: '/echo/json/',
      data: {
        json: json_data,
        delay: 0
      },
      success: function(response) {
        console.log(response);
        $("#tags").autocomplete({
          source: response,
          search: null
        });
      },
      dataType: "JSON"
    });


  });
});

https://jsfiddle.net/sfn8pd3a/

Sign up to request clarification or add additional context in comments.

4 Comments

Does not seem to work, I return the myNewSource/response as ["foo1", "foo2", "foo3"], but the autocomplete is still not working.
Hello, I did a working example here jsfiddle.net/sfn8pd3a, Have a great day.
And it works, except it's not source: response but source: response.split(","). Technically everyone wrote the same, but I can only accept one.
I mean, it returned the response as a string, not as an array, and could not process it.
1

Try something like this where newSet is the new set of predefined names

$.ajax({ //jadajada
url: "url",
type: "post", //send it through get method
data: {
  method: "baz",
  foo: bar
},
success: function(response) {
    document.getElementById("bal").innerHTML = response;
$( "#autocomplete" ).autocomplete('option', 'source', newSet)
},                                                              
error: function(xhr) {
  //Do Something to handle error
}
});

2 Comments

Does not seem to work, I return the newSet/response as ["foo1", "foo2", "foo3"], but the autocomplete is still not working.
@kry are you sure that the respone is as ["foo1", "foo2", "foo3"]. You can use console.log(response) in the success function to be certain that it in correct format
1

Why not using the same function that you use on load ? Just load the responses after success.

$.ajax({ //jadajada
      url: "url",
      type: "post", //send it through get method
      data: {
        method: "baz",
        foo: bar
      },
      success: function(response) {
          $( "#foo-teszt" ).autocomplete({
                source: response
              });
      },                                                              
      error: function(xhr) {
        //Do Something to handle error
      }
    });

1 Comment

This doesn't seem to work at the moment, I'm returning the array as ["foo1", "foo2", "foo3"], and using it as the source, but it's not showing anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.