Missing understanding on Javascript function

4054 views javascript
1

I have a generic MVC aspnetcore setup, that pulls data from a local DB that is full with all USA zip codes, the state and city they are associated with. I am trying to pull back suggestion after say 3 digits are put in for what state they should be inferring and then to fill in the missing city after 5 digits are placed in the textbox. The issue that is baffling me is that within the javascript function data has the returned information. But that information is lost once the scope has left the function and also trying to set the value of another textbox to any of that information fails.

My view

@section Scripts{
     <script src="Scripts/jquery-1.5.min.js" type="text/javascript"></script>
     <script src="~/js/data.js" type="text/javascript"></script>
}
<div class="form-group">
    <label asp-for="Zip" class="col-xs-2 control-label"></label>
    <div class="col-xs-6">
        <input id="Zip" asp-for="Zip" class="form-control" onkeyup="loadData()"/>
        <span asp-validation-for="Zip" class="text-danger" />
    </div>
</div>

My javascript file

function loadData() {
     var str = $("#Zip").val();
     if (str.length == 3){
        $.get("/Localities/OnChange", { id: str }, function (data) {
            $("#Code").val(data.code);
        });
    }
    if (str.length == 5) {
        $.get("/Localities/OnChange", { id: str }, function (data) {
            $("#Boroughs").val(data.boroughs);
            $("#City").val(data.city);
            $("#Code").val(data.code);
            $("#Country").val(data.country);
            $("#County").val(data.county);
            var temp = data.city;
        });
    }
}

My controller

 [HttpGet]
    public Localities OnChange(string id)
    {
        Localities temp = _context.Localities.FirstOrDefault(x => x.Zip.StartsWith(id));
        var temp2 = JsonConvert.SerializeObject(temp);
        return temp;
    }

answered question

..because data is an argument passed to your $.get callback function, so it's scope is within that function. If you want it to be scoped somewhere else, you have to push it somewhere else, like a global variable or some other namespaced variable designated to store/reference things of this nature.

Super basic example to get point across: window.data = data; this will push it to a globally (window) scoped variable of the same name. This is generally bad practice, though. Better to push it to some data handler layer.

I believe I tried passing it to a variable within the loadData function and it wouldn't do that, just like its not setting any of the textbox values; so even though I haven't tried created a more global value in the view not sure how that would give a different outcome.

I understand proper wrappers can easily blow up code. As to understanding ajax (not fully) but my main issue is probably why after it leaves the .get having sent the response when the data finally does get returned how do I go about finally populating the information like I am trying to do.

1 Answer

3

There is few potential issues here:

1) In this code here:

function loadData() {
     var str = $("#Zip").val();
     if (str.length == 3){
        $.get("/Localities/OnChange", { id: str }, function (data) {
            $("#Code").val(data.code);
        });
    }
    if (str.length == 5) {
        $.get("/Localities/OnChange", { id: str }, function (data) {
            $("#Boroughs").val(data.boroughs);
            $("#City").val(data.city);
            $("#Code").val(data.code);
            $("#Country").val(data.country);
            $("#County").val(data.county);
            var temp = data.city;
        });
    }
}

var temp in second GET will only be available with in the function that is in now.

Second which is most likely why your code is not showing data is because it is most likely

data.data.city and data.data.code and so on

if you do console.log(data); I am pretty sure it is nested with in another data wrapper.

Let me know I would change function variable to function(response) so you are note confused by the level you are at.

This should work or at least give you a better idea of what is broken:

var temp; // Global

function loadData() {
         var str = $("#Zip").val();
         if (str.length == 3){
            $.get("/Localities/OnChange", { id: str }, function (response) {
                $("#Code").val(response.data.code);
            });
        }
        if (str.length == 5) {
            $.get("/Localities/OnChange", { id: str }, function (response) {
                $("#Boroughs").val(response.data.boroughs);
                $("#City").val(response.data.city);
                $("#Code").val(response.data.code);
                $("#Country").val(response.data.country);
                $("#County").val(response.data.county);
                temp = response.data.city;
            });
        }
    }

Also check your console for any other errors, that may be preventing the code from executing.

posted this

Have an answer?

JD

Please login first before posting an answer.