I am new to programming with django and now I am stuck at this stage, where I have to move data from the js variable to Django view or something. But at the moment if I try to pass the data from js to Django using ajax post function it says uncaught range error. I am not sure where I am making the mistake but it would be really helpful if anyone can help me. Really indeed of help PLS!!!
Error message:
Uncaught RangeError: Maximum call stack size exceeded at Dt (jquery.min.js:2)
Script code
<script>
var URL = "{% url 'textFromInputFile' %}";
var textOfFile = document.getElementById('fileinput');
textOfFile.addEventListener('change', function(){
var fr = new FileReader();
fr.onload = function(){
document.getElementById("textarea").value = fr.result;
};
fr.readAsText(this.files[0]);
});
function getText(){
$.ajax({
type: "POST",
url: "/textFromInputFile",
data: {"textOfFile":textOfFile},
dataType: "String",
success: function(data){
alert("ok")
},
failure:function(){
alert("failed")
}
},);}
$('button').click(function(){
getText();
});
</script>
views.py
def textFromInputFile(request):
if request.method == 'POST':
if 'textOfFile' in request.POST:
textOfFile = request.POST['textOfFile']
#need to do something here
return HttpResponse('success') #if everything is o.k
else:
return HttpResponse('failed!!')
urls.py
urlpatterns = [
path('', views.index, name='index'),
path('signin.html', views.signin, name='signin'),
path('index.html', views.index, name='index'),
path('home.html', views.home, name='home'),
path('logoutPage.html', views.logout, name='logout'),
path('home.html', views.textFromInputFile, name='textFromInputFile'),
]
The error can be caused by multiple Ajax attempts to serialize your JSON. So we better serialize it before sending it using JSON.stringify () Try changing yor ajax function, the data like this:
data:JSON.stringify({"textOfFile":textOfFile}),
The other way is jus adding this to the ajax function:
$.ajax({
type: "POST", url: "/textFromInputFile",
data: {"textOfFile":textOfFile},
dataType: "String",
success: function(data){
alert("ok")
},
failure:function(){
alert("failed")
},
cache: false,
contentType: false,
processData: false,
},);