0

So I have a form with some fields and then radio buttons that will change the last part of the form using Ajax. I am able to do this part, but now I have to load some data in the form. The data give me the form's last part and the values to put in the fields of that part.

Here's the problem: While Ajax loads the last fields (depending on the checked radio button), my script continues and inserts the data in the form, so when the last fields remain empty (they were not done loading..)

Here's a part of my code:

$('input[name=radioName]').each(function(){
    if($(this).val() == radioValueToCheck){
        $(this).prop('checked', true);
        changeType(this); //my function that loads the ajax and put it in the form
    }
});

alert(document.getElementById('TypeDiv').innerHTML); //div still not updated

$.each(formData, function(index, fieldName){
    setNewValue(fieldName, infoExpense[fieldName]); //custom function to insert new values
});

alert(document.getElementById('TypeDiv').innerHTML); //NOW the div is updated!.... =/

The form still end up updated, so I believe the problem is not with the ajax function..

Puroto
  • 153
  • 1
  • 3
  • 16
  • 2
    Your ajax code runs *asynchronously* (that's the A part in AJAX) - so `changeType` code will not occur until after your other code has run. When you use an `alert`, you're effectively pausing the method until you close the alert which gives the ajax call time to run/return so your second alert has the value because the ajax has completed by the time it runs. Change both to `console.log` and both will appear to be not updated. See the duplicate for more info. – freedomn-m Feb 28 '17 at 20:56
  • So if I get it right, I can move my loop in the `ajax().done(function(){ //my function })` to make it work. – Puroto Feb 28 '17 at 21:23
  • 1
    that looks about right. – freedomn-m Feb 28 '17 at 21:36

0 Answers0