简体   繁体   中英

Jquery append after ajax not working every time

I have a problem with jquery append. This is the code:

$.ajax({
    method: "POST",
    url:
        "/getcars.php",
    data: {
        model_car: sessionStorage.getItem("model")
    }
}).done(function(msg) {
    var obj = JSON.parse(msg);
    $("#model").empty().append('<option value="-1">Model</option>');
    var string_option = "";
    Object.keys(obj.model).forEach(function(key) {
        string_option += '<option value="' + obj.model[key] + '">' + obj.model[key] + '</option>';
    });
  
    console.log(string_option);
    $("#model").append(string_option);
})

This code work very well, but not every time. (only the append option not working. This: console.log(string_option) it`s ok every time).

Can you help me, please?

Thank you!!

Looks like you need to put the code to be executed after the document is fully loaded using the "$( document ).ready" jQuery event

$( document ).ready(function() {

    $.ajax({
        method: "POST",
        url:
            "/getcars.php",
        data: {
            model_car: sessionStorage.getItem("model")
        }
    }).done(function(msg) {
        var obj = JSON.parse(msg);
        $("#model").empty().append('<option value="-1">Model</option>');
        var string_option = "";
        Object.keys(obj.model).forEach(function(key) {
            string_option += '<option value="' + obj.model[key] + '">' + obj.model[key] + '</option>';
        });
      
        console.log(string_option);
        $("#model").append(string_option);
    })

});

You can learn more about this on the below link https://api.jquery.com/ready/

One possible problem could be that you run the .append() before DOM is loaded. If this is the problem you can try 2 methods:

  • put this javascript code inside footer.
  • add to your code:
$(document).ready(function(){
     //... your ajax request
})

Try to check the response on Ajax success sometimes it happens due to malformed JSON is sent back with a 200/OK

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM