Exploring the world of Ajax without jQuery Library has been quite a journey. I recently created a basic view that displays a random number on the screen. After adding a button and invoking the ajax function, I encountered an issue where clicking the button did not update the displayed value. Upon inspecting the DOM (using firebug), I discovered that the someText.responseText was returning the entire HTML instead of just the new value. Despite my efforts, like checking "request.is_ajax()" and examining the request for any signs of ajax, I couldn't seem to make it work as expected. This experience has brought me face to face with the complexities of Django and how to handle them effectively.
I have shared snippets of my code below:
def home(request):
rand_num = random.randint(1, 100)
return render(request, 'home.html', {'rand_num': rand_num})
And here is the corresponding HTML and script:
<html>
<head>
<script type='text/javascript'>
var someText;
function helloWorld(){
someText = new XMLHttpRequest();
someText.onreadystatechange = callBack;
someText.open("GET", "{% url 'home' %}", true);
someText.send();
};
// Handling server response
function callBack(){
if(someText.readyState==4 && someText.status==200){
document.getElementById('result').innerHtml = someText.responseText;
}
};
</script>
</head>
<body>
<div id="result">{{ rand_num }}</div>
<input type='button' value='Abraca dabra!' onclick="helloWorld()"/>
</body>
</html>
Lastly, here is the URL mapping for the view in question:
url(r'^$', 'socialauth.views.home', name='home'),
As I continue learning through online tutorials, your guidance and support are highly appreciated.