0

I have this jquery function and it fails after the form submission and never completes the second AJAX call. I'm not sure what I'm doing wrong or how I could write it differently to ensure that this does not happen. Other similar functions fail sporadically. In other words sometimes the second AJAX call is completed and sometimes it is not. I'm still learning, so please be patient with me.

$(document).ready(function(){
//Add the new player information through the Add Player button
$("#newPlayer_btn").click(function(){
    var pn = $("#playerName").val();
    var cn = $("#charName").val();
    var cc = $("#charClass").val();
    var cr = $("#charRace").val();
    var cl = $("#charLevel").val();

    var dataString = 'playerName='+ pn + '&charName='+ cn + '&charClass='+ cc + '&charRace='+ cr + '&charLvl=' + cl;
    // AJAX Code To Submit Form.
    $.ajax({
        type: "POST",
        url: "new_player.php",
        data: dataString,
        cache: false
    });

    //Reset the form after submission
    $("#newplayerform")[0].reset();

    //Add the player to the navigation menu.
    $.ajax({
        type: "POST",
        url: "player_tab.php",
        cache: false,
        success: function(postresult){
            $("#playernav").html(postresult);
        }
    });

    return false;
});

});

One thing to note is that I have multiple subfunctions for other buttons under the main document.ready function. All of which have the same basic format. Am I misunderstanding something about how I should set this up? I can't figure out why some function calls work and others do not.

  • your 2 calls to ajax are asynchronous, so its not waiting for it complete and going to the next statement. [See this](https://stackoverflow.com/a/14465276/7177029) to schedule your 2 ajax to complete in sequence – Kunal Mukherjee Jan 09 '19 at 14:53
  • Oh, that makes a lot of sense. How would I go about fixing that? What I want it to do is wait for the form to submit then re-read the database and repopulate the navigation menu. I'm at a loss as to how to complete that without the second ajax call. – Kristen Miller Jan 09 '19 at 14:56
  • Nevermind. I think I can just fix my backend and do it that way. Thanks for the information. – Kristen Miller Jan 09 '19 at 14:57
  • You can use the `$.when` static method to wait for your first ajax to complete then fire your 2nd ajax – Kunal Mukherjee Jan 09 '19 at 14:58
  • Thank you. That helps a lot. – Kristen Miller Jan 09 '19 at 15:05

0 Answers0