Update div with jQuery ajax response html

thedeepfield picture thedeepfield · Aug 5, 2013 · Viewed 209.6k times · Source

I am trying to update a div with the content from an ajax html response. I beleive I have the syntax correct, however the div content gets replaced with the entire HTML page response, instead of just the div selected in the html response. What am I doing wrong?

    <script>
        $('#submitform').click(function() {
            $.ajax({
            url: "getinfo.asp",
            data: {
                txtsearch: $('#appendedInputButton').val()
            },
            type: "GET",
            dataType : "html",
            success: function( data ) {
                $('#showresults').replaceWith($('#showresults').html(data));
            },
            error: function( xhr, status ) {
            alert( "Sorry, there was a problem!" );
            },
            complete: function( xhr, status ) {
                //$('#showresults').slideDown('slow')
            }
            });
        });
    </script>

Answer

adeneo picture adeneo · Aug 5, 2013

You are setting the html of #showresults of whatever data is, and then replacing it with itself, which doesn't make much sense ?
I'm guessing you where really trying to find #showresults in the returned data, and then update the #showresults element in the DOM with the html from the one from the ajax call :

$('#submitform').click(function () {
    $.ajax({
        url: "getinfo.asp",
        data: {
            txtsearch: $('#appendedInputButton').val()
        },
        type: "GET",
        dataType: "html",
        success: function (data) {
            var result = $('<div />').append(data).find('#showresults').html();
            $('#showresults').html(result);
        },
        error: function (xhr, status) {
            alert("Sorry, there was a problem!");
        },
        complete: function (xhr, status) {
            //$('#showresults').slideDown('slow')
        }
    });
});