0

I am currently using a JQuery code and a JSON file to load cities in a select> according to the chosen state/province. The JQuery is below.

$(document).ready(function() {

    $.getJSON('../../../js/statesCities.json', function(data) {
        var items = [];
        var options = '<option value="">Selecione</option>';
        $.each(data, function(key, val) {
            options += '<option value="' + val.sigla + '">' + val.sigla + '</option>';
        });
        $("#estados").html(options);

        $("#estados").change(function() {

            var options_cidades = '<option value="">Selecione</option>';
            var str = "";

            $("#estados option:selected").each(function() {
                str += $(this).text();
            });

            $.each(data, function(key, val) {
                if (val.sigla == str) {
                    $.each(val.cidades, function(key_city, val_city) {
                        options_cidades += '<option value="' + val_city + '">' + val_city + '</option>';
                    });
                }
            });
            $("#cidades").html(options_cidades);

        }).change();

    });

});});

The JSON code I am using: https://gist.github.com/letanure/3012978

And the HTML selects:

<div>
    <b>Estado:</b>
    <select id="estados" class="form-control" name="estadoCliente" required>
        <option value="">Selecione</option>
    </select>
</div>
<div>
    <b>Cidade:</b>
    <select id="cidades" class="form-control" name="cidadeCliente" required>
        <option value="">Selecione</option>
    </select>
</div>

In fact, this code works just fine. But when I want to fill a form using PHP data, the code doesn't help. (The registration page is the same as editing. On the edition page, PHP loads user's information). If all the states and cities were pre-loaded in the HTML (Have all options typed), in order to check which state and city are in the database, I would use an inline PHP's if, considering the variable $state as the state of any user who filled in this form.

<option <?php echo $state=='AB'?'selected': ''?>>AB</option>

But It can't be used because the function $.each won't accept the variables from PHP. So, my question is how can I do this verification to each option, having the state and city saved in a database? I will use this code to load the data of a user, so I can edit information more easily.

PS: I don't know how I could better describe this question on the title.

10
  • What is the question exactly. As far as I understand your post, you are able to generate your selects using javascript and now you would like to do the same thing using PHP if the user is already registered and make their city and province pre-selected? Have you tried some things or don't you even know where to start? Commented May 13, 2018 at 18:56
  • Somehow I get the feeling you don't know php is a server language. You just don't in line a php statement and expect php will respond to a JavaScript change event. Commented May 13, 2018 at 18:57
  • @Lou I have this registration page, where the admin is able to register users. But I programmed it in a way that the editing page is the same as the registration. So, when editing a user, the system must load the data from the database, and make the comparison. Gotcha? Commented May 13, 2018 at 20:14
  • @Xorifelse Of course I know that. The PHP is not part of the algorytm that load cities. Actually, that inline code is used on editing page, to check what is the state and the city of a user, and put a 'checked' attr on the corresponding option. Did you understand? Commented May 13, 2018 at 20:23
  • @GuilhermyCamargo and what is the database technology that you use? Commented May 13, 2018 at 20:23

1 Answer 1

1

Because you're loading the data on the frontend you will need to store the backend values somewhere, then once the data has loaded, use the JS to compare and select the correct option.

In your html you could do (supposing you're not using a templating engine):

<div>
    <b>Estado:</b>
    <select id="estados" class="form-control" name="estadoCliente" initial-val="<?php $estado; ?>" required>
        <option value="">Selecione</option>
    </select>
</div>
<div>
    <b>Cidade:</b>
    <select id="cidades" class="form-control" name="cidadeCliente" initial-val="<?php $cidade; ?>" required>
        <option value="">Selecione</option>
    </select>
</div>

Above you should see the use of initial-val="...", you can call this whatever you want. You will use these values when the data loads...

So, your JS would now use those, like so:

$(document).ready(function() {

    $.getJSON('../../../js/statesCities.json', function(data) {
        var items = [];
        var options = '<option value="">Selecione</option>';
        $.each(data, function(key, val) {
            options += '<option value="' + val.sigla + '">' + val.sigla + '</option>';
        });

        // always cache your jquery dom lookups in a var if queries more than once.
        var $estados = $("#estados");
        var $cidades = $("#cidades");

        $estados.html(options);
        $estados.change(function() {

            var options_cidades = '<option value="">Selecione</option>';
            var str = "";

            $("option:selected", $estados).each(function() {
                str += $(this).text();
            });

            $.each(data, function(key, val) {
                if (val.sigla == str) {
                    $.each(val.cidades, function(key_city, val_city) {
                        options_cidades += '<option value="' + val_city + '">' + val_city + '</option>';
                    });
                }
            });
            $cidades.html(options_cidades);
            $cidades.val($cidades.attr("initial-val"));

        }).change();

        // now set the value on the "estados" <select> and trigger the change event, so the above code runs to change "cidades"
        $estados.val($estados.attr("initial-val")).trigger( "change" );

    });

});});

That, I hope gets you a solution you can build upon.

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

15 Comments

Dude, really thank you for the answer. But I think your code adaptation is only focused on loading the cities of the selected state. What I need is to check what is the state and city of a specific client (whose data, is loaded on PHP), who has already filled the form. Am I right, or did not I understand what you did?
I guess I didn't understand your question then. I'm not sure I do even now. This code change allows your form to essentially restore the values the user had previously selected and likely saved to your database in a previous session/page load.
My problem is the registration page is the same as the editing page. So, when it is loaded to edit user's information, the code must check what state and the city were selected.
@GuilhermyCamargo but has the information been saved? If so, then my suggested answer would solve the problem you are facing. It will reselect the options the user selected. Have you tried it?
Yes. The data is saved in a MySQL database. Yeah, I tried your solution. When I am at the editing page the selects get like (image.ibb.co/jCWhTy/aaa.png).
|

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.