Why does localstorage store the wrong value?

I am having problems with my localstorage. I have a few dependent dropdowns that are loaded via ajax from a server. When the user makes a selection the localstorage stores the wrong value (the last value). From my research I thought that .map() may be a solution to my problem but being a newbie I am not familiar with the syntax and I have not been able to get it to work. Can anyone figure out what is causing this problem? Is .map() the correct solution? Here is a photo of what I am having an issue with.

Here is the code:

$('.country').on('change', function () {
        var countryId = $(this).val();            
        var state_select = $(this).closest('form').find('.state');
        var city_select = $(this).closest('form').find('.city');            

        if (countryId) {
            $.ajax({
                type: 'POST',
                dataType: 'JSON', 
                url: 'ajaxData3.php',
                data: {
                    country_id: countryId
                },                     
                success: function (r) {
                    console.log('States', r);

                    $(state_select).html('<option value="" selected="selected">State</option>');
                    $(city_select).html('<option value="" selected="selected">City </option>');

                    if (r.status) {
                        r.data.forEach(function (state) {
                            $(state_select).append(`<option value="${state.id}">${state.name}</option>`);

                            $('.state').each(function(r) {
                                var stateList = $(state);
                                var thisSelection = $(this);
                                var thisId = thisSelection.attr('id');
                                var storageId = 'state-' + thisId;
                                var storedInfo = JSON.parse(localStorage.getItem(storageId));                                


                                thisSelection.change(function(i) {                                   
                                    var selectedOptions = []; // create an array to hold all currently selected options 

                                    thisSelection.find('option:selected').each(function(i) {
                                        var thisOption = $(this);
                                        selectedOptions.push(thisOption.val());                                           
                                    });

                                    localStorage.setItem(storageId, JSON.stringify(state.name));                                       

                                })                                  

                            })

                        })

                    } else {

                        $(state_select).html('<option value="" selected="selected">Unavailable </option>');
                        $(city_select).html('<option value="" selected="selected">Unavailable </option>');
                    }

                }
            })
        };

Here is the markup

<form id="form1" autocomplete="off">
    <select id="country1" class="country" name="country">
        <?php include("countryAjaxData.php"); ?> 
    </select> 
    <select id="state1" class="state" name="state">
        <option value="" selected="selected">Select state</option>
    </select> 
    <select id="city1" class="city" name="city">
        <option value="" selected="selected">Select city</option> 
    </select>
</form>
<form id="form2" autocomplete="off">
    <select id="country2" class="country" name="country">
        <?php include("countryAjaxData.php"); ?> 
    </select> 
    <select id="state2" class="state" name="state">
        <option value="" selected="selected">Select state</option>
    </select> 
    <select id="city2" class="city" name="city">
        <option value="" selected="selected">Select city</option> 
    </select>
</form>
<form id="form3" autocomplete="off">
    <select id="country3" class="country" name="country">
        <?php include("countryAjaxData.php"); ?> 
    </select> 
    <select id="state3" class="state" name="state">
        <option value="" selected="selected">Select state</option>
    </select> 
    <select id="city3" class="city" name="city">
        <option value="" selected="selected">Select city</option> 
    </select>
</form>
1 Like

i need know the code inside ajaxData3.php and countryAjaxData.php to find the problem .
if you don’t mind can you share full project.

1 Like

Hello Fatma, thanks for your reply. I am pretty sure my problem is in the jQuery because everything loads into the forms perfectly and consistently without fail (see photo). The problem occurs when the localstorage engages after the data is already loaded on the webpage. The data in the dropdown is complete but it just fails to be recognized by localstorage . Localstorage only saves the very last entry in the dropdown list. However, I will paste the relative php code here.

$query = $my_connection_code->query("SELECT * FROM countries ORDER BY name ASC;");    
$rowCount = $query->num_rows;    
if($rowCount > 0)		
	{
echo '<option value="">Country</option>';        
    while($row = $query->fetch_assoc())
	{
        echo '<option value="'.$row['id'].'">'.$row['name'].'</option>';
    }
}
else
{
    echo '<option value="">Unavailable</option>'; 
}

$resp = array(
‘status’ => false,
‘data’ =>
);
if (isset($_POST[“country_id”]) && !empty($_POST[“country_id”])) {
$sql = “SELECT id, name FROM states WHERE country_id = " . $_POST[‘country_id’] . " ORDER BY name ASC”;
$query = $my_connection_code->query($sql);
if ($query->num_rows > 0) {
$resp[‘status’] = true;
while ($state = $query->fetch_assoc()) {
$resp[‘data’] = $state;
}
}
echo json_encode($resp);
}

1 Like

I Think I found the problem.
in your .js file you add the localStorage code inside a forEach() i.e.

r.data.forEach(function (state) {
/************all your  the code ************/
 localStorage.setItem(storageId, JSON.stringify(state.name));
}

think if you have two states the above code run two times .for first time it will store the value of state.name to localStorage as storageId and in second time it will again set the value of state.name to localStorage as storageId so each time the code run it will change the value of storageId and in your localStorage you always get the last state name stored in r.data .

the solution of this problem is following :

$('.country').on('change', function () {
        var countryId = $(this).val();            
        var state_select = $(this).closest('form').find('.state');
        var city_select = $(this).closest('form').find('.city');   
		
        if (countryId) {
            $.ajax({
                type: 'POST',
                dataType: 'JSON', 
                url: 'ajaxData3.php',
                data: {
                    country_id: countryId
                },                     
                success: function (r) {
                    console.log('States', r);

                    $(state_select).html('<option value="" selected="selected">State</option>');
                    $(city_select).html('<option value="" selected="selected">City </option>');

                    if (r.status) {
                        r.data.forEach(function (state) {
                            $(state_select).append(`<option value="${state.id}">${state.name}</option>`);

                            $('.state').each(function(r) {
                                var stateList = $(state);
                                var thisSelection = $(this);
                                var thisId = thisSelection.attr('id');
                                var storageId = 'state-' + thisId;
                                var storedInfo = JSON.parse(localStorage.getItem(storageId));                                


                                thisSelection.change(function(i) {                                   
                                    var selectedOptions = []; // create an array to hold all currently selected options 

                                    thisSelection.find('option:selected').each(function(i) {
                                        var thisOption = $(this);
                                        selectedOptions.push(thisOption.val()); 
                               localStorage.setItem(storageId,JSON.stringify(thisOption.text()));                                          
                                    });

                                })                                  

                            })

                        })

                    } else {

                        $(state_select).html('<option value="" selected="selected">Unavailable </option>');
                        $(city_select).html('<option value="" selected="selected">Unavailable </option>');
                    }

                }
            })
        };
})

change the localStorage.setItem(storageId, JSON.stringify(state.name)) to localStorage.setItem(storageId,JSON.stringify(thisOption.text())); and put this line inside thisSelection.change(function(i) { }) function.
it will checks whether the Element contains .state class value changes and the value selected by user will be stored to localstorage .

1 Like

Hello Fatma, this is great. I knew my jQuery/javascript was the problem. My javascript skills need much, much more help as well as my javascript logic.

1 Like

I am happy to see that you found my solution helpful.

1 Like

Thanks again. I wish you tutored or had a javascript course.

1 Like

Thanks, but FatmaNagori figured out the problem a few months ago as you can see above.

1 Like