My WCF REST service works fine, getJSON() and autocomplete() also work – BUT the result of the call to the WCF service is null unless I set a debug point in Firebug. If I don’t set a debug point the getJSON method will only return the JSON some of the time.
It seems that the getJSON method doesn’t wait for a response from my WCF service – which can take a second or two. Putting a debug point in my jQuery causes the script to “pause” while the WCF has time to return the JSON:
// Changing the selected item of the DropDownList will submit a different clientId
// to the WCF service. The result is used for the autocomplete()
$(document).ready(function () {
var availableTags = "";
$('#<%=ddlClients.ClientID %>').change(function () {
var selectedClientId = $('#<%=ddlClients.ClientID %> option:selected').val();
if (selectedClientId != -1) {
//$.ajaxSetup({ async: false });
$.getJSON("People.svc/getpeople", { ClientId: selectedClientId }, function (json) {
availableTags = json;
});
//$.ajaxSetup({ async: true });
$('#tbSearch').autocomplete({
source: availableTags,
minLength: 2
});
}
});
});
The only thing I came up with was to disable async post backs while calling getJSON (which I commented out above), but I feel like this is a hack.
Considering how common WCF REST services and jQuery/Ajax are, I betting there’s another solution to this – or is disabling async postbacks the right way?
You are trying to use the
availableTagsbefore it is assigned, the success function will be called when your request is completed, the code after the getJSON call will be executed immediately. Ti use the data returned by the success callback I suggest you put your code in the callback itself.