简体   繁体   中英

How do i update a div tag after a ajax call?

I have script with multiple buttons which when clicked run a php script via AJAX. I would now like the result to show in the div with the button. I have tried this and parent but neither work.

Example below: when clicked on .showme I want the result to show in the #here div within the same its parent.

 $(document).ready(function() { $('.showme').bind('click', function() { var id = $(this).attr("id"); var num = $(this).attr("class"); var poststr = "request=" + num + "&moreinfo=" + id; $.ajax({ url: "../../assets/php/testme.php", cache: 0, data: poststr, success: function(result) { $(this).getElementById("here").innerHTML = result; } }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='request_1 showme' id='rating_1'>More stuff 1 <div id="here"></div> </div> <div class='request_2 showme' id='rating_2'>More stuff 2 <div id="here"></div> </div> <div class='request_3 showme' id='rating_3'>More stuff 3 <div id="here"></div> </div> 

I think this will do:

$(document).ready(function () {
    $('.showme').bind('click', function () {

        //keep the element reference in a variable to use in ajax success
        var _this = $(this);

        var id = $(this).attr("id");
        var num = $(this).attr("class");
        var poststr = "request=" + num + "&moreinfo=" + id;
        $.ajax({
            url: "../../assets/php/testme.php",
            cache: 0,
            data: poststr,
            success: function (result) {
                //use the element reference you kept in variable before ajax call instead of $(this)
                //also use jQuery style, getElementById is undefined if you call after $(this)
                //.find() will call it's child in any level, also better you use classes instead of using same id multiple times
                _this.find("#here").html(result);
            }
        });
    });
});

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