Bchadwick Bchadwick - 3 months ago 11
Ajax Question

Django Insert html into div using jquery .ajax() on button click

I need help inserting html into an empty div using .ajax(). I have the code below in a django project. The view and url work fine as does the alert message of the ajax .click function. The .ajax() 'success:' property is underlined as unused in pycharm.

The view is as follows:

def gen_teams(request):
return HttpResponse("<h1>Hello World</h1>")


urls:

url(r'^gen_teams/$', home_views.gen_teams, name='gen_teams'),


main.js:

$('#ajaxSubmit').click(function(){
alert('Creating Teams');
var ajaxDiv = $('#ajaxContent');
$.ajax({
url:"http://127.0.0.1:8000/gen_teams/",
datatype:"html",
type: "POST",
success: function(data) {
ajaxDiv.replaceWith(ajaxDiv.html(data));
}
});
});


HTML:

<p><button id="ajaxSubmit" class="btn btn-primary" onclick="">Ajax teams</button></p>
<div id="ajaxContent" class="content-container">

</div>

Answer

Try replacing:

ajaxDiv.replaceWith(ajaxDiv.html(data));

with:

$('#ajaxContent').html(data);
Comments