Why Ajax is triggering 500 internal error in django? - javascript

Does anyone know why I am getting 500 internal error when I try to call an Ajax function? I tried to send the response from view.py to Ajax function in 2 ways: JsonResponse (see else from view.py) and also with HttpResponse (see if from View.py).
My Hmtl form does have a csrf_token, so I added the header in ajax function, but still got 500 internal erorr. The data is saved into database but the response is not sent to ajax function.
View.py
## Ajax
#login_required
def SubmitModal(request):
if request.method == 'POST':
text = request.POST['Text']
date = request.POST['DatePicker']
time = request.POST['TimePicker']
T = SText()
T.User = request.user
T.Text = text
T.STime = date + ' ' + time
T.save()
return HttpResponse(json.dumps({'success': True}), content_type="application/json")
else:
return JsonResponse({'success': False})
file that contains ajax
$(document).ready(function () {
// Show the modal window when a button is clicked
$('#open-modal').click(function () {
$('#modal').modal('show');
});
// Close the modal window when a button is clicked
$('.close-modal').click(function () {
$('#modal').modal('hide');
});
// Handle the form submission
$('#modal-form').submit(function (event) {
event.preventDefault(); // Prevent the form from being submitted
var formData = $(this).serialize(); // Get the form data
// Submit the form data to the server using an AJAX request
$.ajax({
type: 'POST',
url: '/submit/',
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: formData,
dataType: "json",
success: function (response) {
if (response.success) {
$('#success-message').show();
} else {
$('#error-message').show();
}
},
error: function (xhr, status, error) {
console.log(error);
}
});
$(".textarea-input")[0].value = '';
$(".date-input")[0].value = '';
$(".time-input")[0].value = '';
});
});

If you're reproducing this in a non-production environment, you can set DEBUG=True in the settings file. Then when you make the call from your browser, the response will include details about what the issue is. You can also set the ADMINS variable to send exception tracebacks to the specified emails when they're encountered. More details here.
You can view the data being sent and received in the developer tools of the browser you are using.

Related

How to display search results with ajax in django project?

I am working in a Django project where one of the functionalities will be that user could search a name (using a form), the view will search that name in database (after some transformation), and the results will be displayed below the form.
At the moment, It is necesary that the entire page loads every time a search is submitted. I am working in apply ajax to make this dynamic. The problem is that when I return the search result as a JsonResponse, I am not able to see the data in the success function of ajax.
Views.py
def indexView (request):
form = FriendForm ()
friends = Friend.objects.all ()
return render (request, "index.html", {"form": form, "friends": friends})
def searchFriend(request):
if request.method =="POST":
form = FriendForm (request.POST)
if form.is_valid():
if request.is_ajax():
name = form.cleaned_data['name']
query = Friend.objects.filer(first_name__contains=name)
print(query)
return JsonResponse(list(query), safe=False)
else:
return JsonResponse(form.errors)
Main.js
$(document).ready(function() {
$("#form1").submit(function() { // catch the form's submit event
var search = $("#searchField").val();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
method: 'post',
dataType: 'json',
url: "search/ajax/friend/",
success: function(data) { // on success..
console.log(data)
}
});
return false;
});
});
Is your query getting printed in terminal ?
Friend.objects.filer use filter instead of filer
and use type: 'post' instead of method: 'post',
and add data: $(search).serialize(), instead of data: $(this).serialize(),

Django - .ajax() method is not working properly

I'm writing Ajax code to hit the database to edit model instances. But the code is not working well. The first alert statement does work, but not the other alert statements. Code in success or error does not respond. Everything seems good. I have no idea how this happened though.
book/detail.html:
<script>
$(document).ready(function () {
$("#add").click(function() {
alert('clicked');
$.ajax({
url: '{% url "cart:add_to_cart" %}',
// handle a successful response
success: function (response) {
alert("Testing.");
("#cartButton").text("Cart" + "(" + response.quantity + ")");
},
error: function (response) {
alert('Got an error');
}
});
});
});
</script>
cart.view.py:
def add_books(request):
c = Cart.objects.get(user=request.user)
q = request.GET.get('quantity')
book_id = request.GET.get('bookID')
<some code here>
response = {
'quantity': BooksInCart.objects.filter(cart=c).aggregate(item_quantity=Sum('quantity'))['item_quantity']
}
return JsonResponse(response)
cart.urls:
app_name = 'cart'
urlpatterns = [
path('add_books/', views.add_books, name='add_to_cart')
]
If you are changing data in the database, you should be using a post-type request. Include method: 'POST' and the csrf token in your ajax call and then check for for a post-type request in your view:
if request.method == 'POST':
To set the csrf token put {% csrf_token %} in your template in order to render the token, and then user JQuery to load the token value into the data portion of the ajax call:
data = {'csrfmiddlewaretoken': $('[name="csrfmiddlewaretoken"]').val()}

handle form request with ajax in django

i have problem with ajax when i send a request from my form it doesn't get the value from the form
this is my view code
def create(request):
if request.method == 'POST':
msg_text = request.POST.get('the_massage')
data = {}
form = ChatApp(message=msg_text, user=request.user)
form.save()
data['message']=form.message
data['user']=form.user.username
return JsonResponse(data)
else:
return JsonResponse({'nothing coming thrue'})
it shod get the_massage variable but it give me null value
this is my ajax function :
$(function () {
$('#main-form').on("submit" ,function () {
console.log("create function is here");
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: {the_massage:$('#msgbox').val()},
dataType: 'json',
success: function(json) {
console.log(json);
console.log('success');
},
error: function(error){
console.log('we have error');
},
});
});
});
when i console log the value it just come through in the console
please help me
and show me this in the console :
Resource interpreted as Document but transferred with MIME type
application/json: "http://localhost:8000/create/".
Call the function in your event:
$('#main-form').on("submit" ,function (event) {
event.preventDefault();
console.log('submited');
console.log($('#msgbox').val())
created();
});
I see many possibles problems here.
1) just for dev propose, delete #login_required (if you have) from your view and add #csrf_exempt to avoid this problem on dev.
2) Please look inside request.body on your view.
3) if point 1 and 2 doesn't work, please put the server response of this call: POST localhost:8000/create 403 (Forbidden)
this is the write answer : i solve this and its on git hub now https://github.com/mhadiahmed/tinypice

not going through the django view through ajax post data

I am doing the login throgh ajax. jquery function is working fine but its not going to the ajax url. So django view is not getting executed.
Ajax.html
$(function()
{
localStorage['domain'] = "http://122.172.64.142";
var domain = localStorage['domain'];
$('#fac1').on('click', function () {
var username = $("#username").val();
var password = $("#pwd").val();
data = {
name: username,
password: password
};
alert(domain);
$.ajax({
url: domain + "/login/login_android_here/",
type: "POST",
data: data,
success: function (response) {
alert("success");
window.location = 'file:///android_asset/www/posts.html';
},
error: function () {
alert('some error in login');
}
});
return false;
});
});
My django views.py
#csrf_exempt
def login_android(request):
print "i am in view"
if request.method == "POST":
print "you are in method"
username = request.POST['name']
password = request.POST['password']
login_api(request,username,password)
#return HttpResponseRedirect('/home/')
messages.success(request, 'You Loged In Successfully')
response = json.dumps(username)
return HttpResponse(response, mimetype="application/json")
When i click on login button i am getting alert but its not getting entered to view. Url is correct.
I would first recommend using Chrome with the developer tools console open.
You could change you alerts for console.log().
When your trying window.location = 'file:///android_asset/www/posts.html';
You are trying to access a local resource. If I post that in my Chrome developer tools I get back
Not allowed to load local resource: file:///android_asset/www/posts.html
If you would use window.location.replace("a url to your view"); this will work like a HTTP redirect.
for more information redirect page
and you should be able to see your view.
I was made a silly mistake. I provided a wrong domain address on this page. Now it worked.
localStorage['domain'] = "http://122.172.64.142";
This address was wrong. Thats why it was not able to enter in to the view.
You forgot dataType ajax param
$.ajax({
url: domain + "/login/login_android_here/",
type: "POST",
data: data,
dataType : 'json', //dataType param IS MISSING
success: function (response) {
alert("success");
window.location = 'file:///android_asset/www/posts.html';
},
error: function () {
alert('some error in login');
}
});

Django + Ajax | File Upload | Server doesn't recognise Ajax Request

I am trying to implement file upload using ajax with Django but facing some problem.
When the user tries to upload the files after selecting the file and submitting the form, then as per my understanding , an ajax request should be send to the server using POST method ,but in my case a POST request is being made to the server, but the server is not able to identify it as an ajax request and browser is redirected to http://<server>:<port>/upload/ and the contents on this page are as follows.
{"status": "error", "result": "Something went wrong.Try Again !!"}
Django Version: 1.6.2
Python Version: 2.7.5
Also, testing on Django Development Server.
views.py
def upload(request):
logging.info('Inside upload view')
response_data = {}
if request.is_ajax():
logging.info('Is_AJAX() returned True')
form = UploaderForm(request.POST, request.FILES)
if form.is_valid():
logging.info('Uploaded Data Validated')
upload = Upload( upload=request.FILES['upload'] )
upload.name = request.FILES['upload'].name
upload.save()
logging.info('Uploaded Data Saved in Database and link is %s' % upload.upload)
response_data['status'] = "success"
response_data['result'] = "Your file has been uploaded !!"
response_data['fileLink'] = "/%s" % upload.upload
return HttpResponse(json.dumps(response_data), content_type="application/json")
response_data['status'] = "error"
response_data['result'] = "Something went wrong.Try Again !!"
return HttpResponse(json.dumps(response_data), content_type='application/json')
Template
<form id="uploadForm" action="/upload/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="fileInput" class="input-file" name="upload" type="file">
<input type="submit" value="Post Images/Files" />
</form>
Javascript 1:
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Javascript 2
var options = {
url: '/upload/',
type: "POST",
error: function(response) {
alert('Something went Wrong. Try Again');
},
success: function(response) {
if ( response.status == 'success' ) {
alert('success');
}
}
};
$('#uploadForm').ajaxSubmit(options);
Question:
1) Why is Django not able to recognize the ajax request and value of request.is_ajax() is always False.
2) Even if the server doesn't recognize ajax request why is my browser getting redirected to another page ?
There is another similar question here but with no result.
This works for me. You need a jquery.form.js
$("#uploadForm").submit(function(event) {
$(this).ajaxSubmit({
url:'{% url upload_file %}',
type: 'post',
success: function(data) {
console.log(data)
},
error: function(jqXHR, exception) {
console.log("An error occurred while uploading your file!");
}
});
return false;
});
Here's the similar question here with answers.
Make sure that javascript code block
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
loaded after your uploadForm html form in DOM on page. In your case seems you trying to bind submit handler with form element which not yet loaded so when you click, it send simple POST request.
1) why is_ajax() not working?
Have you included the JQuery form plugin (jquery.form.js) ? ajaxSubmit() needs that plugin.
Take a look at http://jquery.malsup.com/form/
If it's already done, you might take a look at the HTTPRequest object
Django Documentation says HttpRequest.is_ajax()
Returns True if the request was made via an XMLHttpRequest. And if you are using some javascript libraries to make the ajax request, you dont have to bother about this matter. Still you can verify "HTTP_X_REQUESTED_WITH" header to see if Django received an XMLHttpRequest or not.
2) Why page redirects?
As I said above, JQuery form plugin is needed for handling the ajax request and its call back. Also, for ajaxSubmit() you need to override the $(#uploadForm).submit()
$('#uploadForm').submit( function (){
$(this).ajaxSubmit(options);
return false;
});
Hope this was helpful :)

Categories

Resources