0

I am trying to update user profile. After user inserts his address and submits it converts it to latitude and longitude. I created a conditional statement: if GeocoderStatus is OK then change geoLocationOK = 1 else it is 0. When it is 1 then run the update function, but the latitude and longitude is not passed to formData. On second update click it is added. Any suggestion how can I include the latitude and longitude in formData?

Click to update

        $(document).on("click", "#updateProfile", function (e) {
            function geocodeAddress(geocoder, resultsMap) {
                var address = document.getElementById('address').value;
                geocoder.geocode({'address': address}, function(results, status) {
                    if (status === google.maps.GeocoderStatus.OK) {
                        var latitude = results[0].geometry.location.lat();
                        var longitude = results[0].geometry.location.lng();
                        console.log(latitude);
                        console.log(longitude);
                        userLatitude = document.getElementById('cityLat').value = latitude;
                        userLongitude = document.getElementById('cityLng').value = longitude;
                        geoLocationOK = 1;
                        console.log(geoLocationOK);

                    } else {
                        alert('Geocode was not successful for the following reason: ' + status);
                    }
                });
            }
            geocodeAddress(geocoder);

            if(geoLocationOK == 1){
                updateProfile();
            }else{
                console.log("not ok");
                e.preventDefault();
            }
        });

This is the update function

            function updateProfile(){
                console.log(geoLocationOK);

                $('#rootwizard').formValidation({
                    framework: 'bootstrap',
                    excluded: [':disabled'],
                    icon: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },   
                    live: 'enabled',

                    framework: 'bootstrap',
                    icon: {
                        valid: 'glyphicon glyphicon-ok',
                        invalid: 'glyphicon glyphicon-remove',
                        validating: 'glyphicon glyphicon-refresh'
                    },
                    fields: {
                        userPhoneNr: {
                            validators: {
                                notEmpty: {
                                    message: 'Please insert phone nr'
                                },
                                regexp: {
                                    regexp: /^[a-zA-Z0-9_]+$/,
                                    message: 'Error'
                                }
                            }
                        },
                    }
                }).on('success.form.fv', function(e, data) {
                    // Prevent form submission
                    e.preventDefault();

                    var $form    = $(e.target),
                        formData = new FormData(),
                        params   = $form.serializeArray(),
                        files    = $form.find('[name="userProfilePhoto"]')[0].files;



                    $.each(params, function(i, val) {
                        formData.append(val.name, val.value);
                    });

                    $.ajax({
                        url: $form.attr('action'),
                        data: formData,
                        cache: false,
                        contentType: false,
                        processData: false,
                        type: 'POST',
                        success: function(data){
                            console.log(data);
                            if(data.status == 'success'){

                                getProfileData();     
                            }    
                        },
                        error: function(jqXHR, textStatus, errorThrown, data){
                            console.log(jqXHR, textStatus, errorThrown, data);
                        }
                    });
                    // Now Destroy
                    function destroyFormValidation() {
                        var instance = $('#rootwizard').data('formValidation');
                        if (instance) {
                            instance.destroy();
                        }
                    }
                    destroyFormValidation();
                });
            }
6
  • This is very insecure, I would decide server-side if a profile gets updated. Commented Jul 12, 2016 at 13:19
  • @Robert there is server side verification as well. Commented Jul 12, 2016 at 13:20
  • geocoder.geocode() is async. So set relevant logic in method callback. Commented Jul 12, 2016 at 13:23
  • @A.Wolff thank you for the reply. Can you give any example, since feels like I have tried everything, but nothing works. Commented Jul 12, 2016 at 13:25
  • You should call updateProfile(); from geocoder.geocode() callback. Commented Jul 12, 2016 at 13:29

2 Answers 2

1

Why you only can update on the second click is because on the first click you actually binding the form validation. Why not bind the form validation separately outside the function updateProfile .

And then inside updateProfile submit the form:

function updateProfile(){
     $('#rootwizard').submit();
}
Sign up to request clarification or add additional context in comments.

2 Comments

what if I am using ajax?
Wouldn't that be handled by the form validation callback: on('success.form.fv', function(e, data)
1

Get rid of

        if(geoLocationOK == 1){
            updateProfile();
        }else{
            console.log("not ok");
            e.preventDefault();
        }

and move the call to

updateProfile();

inside your

if (status === google.maps.GeocoderStatus.OK) { ... }

block.

You maybe also still need e.preventDefault(); in there somewhere as well (or you could change the updateProfile element to not be a submit button).

It looks like the geolocation function is asynchronous, which means it it executed in parallel to the other code. Therefore your if (geolocationOK == 1) is almost certain going to run before the function which sets the geolocationOK variable.

In any situation like this with async calls, if you have code which depends on the results of the async call, then that call must be executed within the "success" context of the async call.

1 Comment

the latitude and longitude are still not getting passed for some reason.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.