Database entry not created by clicking on the accept friend request button - javascript

I am writing the view for accepting the friend request, I dont know what is happening,
i am fetching jason data to the view but i doesn't working .
i have tried all of the solutions that are on this website but they doesn't work for me
here is my Javascript
<script >
function acceptFriendRequest(friend_request_id, uiUpdateFunction){
var url = "{% url 'friend:friend-request-accept' friend_request_id=53252623623632623 %}".replace("53252623623632623", friend_request_id)
$.ajax({
type: 'GET',
dataType: "json",
url: url,
timeout: 5000,
success: function(data) {
console.log("SUCCESS", data)
if(data['response'] == "Friend request accepted."){
// ui is updated
}
else if(data['response'] != null){
alert(data['response'])
}
},
error: function(data) {
console.error("ERROR... this is the error from accept", data)
alert("Something went wrong")
},
complete: function(data){
uiUpdateFunction()
}
});
}
Here is my view
def accept_friend_request(request, *args, **kwargs):
user = request.user
payload = {}
if request.method == "GET" and user.is_authenticated:
friend_request_id = kwargs.get("friend_request_id")
# print(f"friend request id {friend_request_id}")
if friend_request_id:
friend_request = FriendRequest.objects.get(pk=friend_request_id)
# print(f"friend request object {friend_request}")
# confirm that is the correct request
if friend_request.receiver == user:
if friend_request:
# found the request. Now accept it
friend_request.accept()
payload['response'] = "Friend request accepted."
else:
payload['response'] = "Something went wrong."
else:
payload['response'] = "That is not your request to accept."
else:
payload['response'] = "Unable to accept that friend request."
else:
# should never happen
payload['response'] = "You must be authenticated to accept a friend request."
return HttpResponse(json.dumps(payload), content_type="application/json")
here is the accept()
def accept(self):
"""
Accept a friend request
update both SENDER and RECEIVER friend lists
"""
receiver_friend_list = FriendList.objects.get(username = self.receiver)
if receiver_friend_list:
receiver_friend_list.add_friend(self.sender)
sender_friend_list = FriendList.objects.get(user = self.sender)
if sender_friend_list:
sender_friend_list.add_friend(self.receiver)
self.is_active = False
self.save()

I often had the problem that I couldn't see the error message (with PHP) with the Jquery Ajax / json return. Change dataType:"json" to "text" and you may see the error message

Related

Ajax not getting sucess reponse from django back-end

I am trying this below requirement where there is a voice synthesizer and it converts my voice (which is a question) into a text and it sends that text to the back-end Django through Ajax.
At the back-end, Django takes that data and use that data (question) to access the database and get the result and send that result to the frontend which should get caught by the success part of the Ajax. But it's not working.
I am not able to figure out where is the problem. I am posting the Ajax and Django code below for your reference.
views.py
def GetAnswer(request):
if request.method=='GET' and request.is_ajax():
question_asked=str(request.GET.get("message_now"))
try:
answer=QuestionAnswer.objects.filter(question=question_asked).value_list('answer', flat=True)[0]
print(answer)
data={"data":answer}
return JsonResponse({"success": True}, data, status=200)
except:
return JsonResponse({"success": False}, status=400)
else:
print("Not Suceess")
main.js
function chatbotvoice(message) {
const speech = new SpeechSynthesisUtterance();
if (message !== null && message !== '') {
$.ajax({
url: "http://127.0.0.1:8000/getanswer",
type: 'GET',
data: {
message_now: message
},
success: function (data) {
speech.text = JSON.parse(data);
window.speechSynthesis.speak(speech);
chatareamain.appendChild(showchatbotmsg(speech.text));
},
error: function (error) {
speech.text = "Oh No!! I don't Know !! I am still learning!! Your question got recorded and answer for your question will be available with me in 24 hours";
window.speechSynthesis.speak(speech);
chatareamain.appendChild(showchatbotmsg(speech.text));
},
});
}
}
I tried to check whether the Ajax request is reaching the function and I am able to view the value of the variable "question_asked" in the back-end.
$.ajax({
crossDomain: true,
url: "{% url 'getanswer' %}",
type: 'GET',
data: {
message_now: message,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
return JsonResponse({"success": True}, data, status=200)
that line will fail with some error message, because you pass data as a second positional argument. Django documentation tells you that second positional argument is encoder. Since a list with data isn't an encoder - you will get an error.
Your error would be catched by try/except block. So the execution flow will move to except block - where you return {"success": false} JSON response.
So your code should become like this:
def GetAnswer(request):
if request.method=='GET' and request.is_ajax():
question_asked=str(request.GET.get("message_now"))
try:
answer=QuestionAnswer.objects.filter(question=question_asked).value_list('answer', flat=True)[0]
print(answer)
data={"data":answer}
return JsonResponse({"success": True, "data": data}, status=200)
except:
return JsonResponse({"success": False}, status=400)
else:
print("Not Suceess")
Please, refer to this part of documentation for more details https://docs.djangoproject.com/en/3.1/ref/request-response/#jsonresponse-objects
UPDATE (21.09.2020)
You should fix this line:
answer=QuestionAnswer.objects.filter(question=question_asked).value_list('answer', flat=True)[0]
to
answer=QuestionAnswer.objects.filter(question=question_asked).values_list('answer', flat=True)[0]
because there's no value_list function, but there's values_list.
UPDATE 2 (21.09.2020)
So the final code should be:
def GetAnswer(request):
if request.method == 'GET' and request.is_ajax():
question_asked = request.GET["message_now"]
try:
answer = QuestionAnswer.objects.filter(question=question_asked).values_list('answer', flat=True)[0]
return JsonResponse({"success": True, "answer": answer}, status=200)
except:
return JsonResponse({"success": False}, status=400)
and JS code should be modified as well
function chatbotvoice(message) {
const speech = new SpeechSynthesisUtterance();
if (message !== null && message !== '') {
$.ajax({
url: "http://127.0.0.1:8000/getanswer",
type: 'GET',
data: {
message_now: message
},
success: function (data) {
if (data.success == true){
speech.text = data.answer;
window.speechSynthesis.speak(speech);
chatareamain.appendChild(showchatbotmsg(speech.text));
} else {
speech.text = "Oh No!! I don't Know !! I am still learning!! Your question got recorded and answer for your question will be available with me in 24 hours";
window.speechSynthesis.speak(speech);
chatareamain.appendChild(showchatbotmsg(speech.text));
}
},
error: function (error) {
speech.text = "Oh No!! I don't Know !! I am still learning!! Your question got recorded and answer for your question will be available with me in 24 hours";
window.speechSynthesis.speak(speech);
chatareamain.appendChild(showchatbotmsg(speech.text));
},
});
}
}

Django Ajax return error messages

How would i return error message with django?
I am thinking something like this ( i am using jsonresponse just as an example of how i want to do this):
def test(request):
if request.method == "POST":
if form.is_valid():
form.save
return JsonResponse({"message":"Successfully published"})
else:
'''here i would like to return error something like:'''
return JsonResponse({"success": false, "error": "there was an error"})
else:
return JsonResponse({"success}: false, "error": "Request method is not post"})
What I am trying to achieve is to render error messages in template from ajax error function. Something like this:
$("#form").on("submit", function(){
$.ajax({url: "url",
data: ("#form").serialize,
success: function(data){
alert(data.message);
},
error: function(data){
alert(data.error);
}
});
Would that be possible?
You can of course return error messages from your Django App. But you have to define what type of error you want to return. For this purpose you'll have to use error codes.
The most known are 404 for page not found or 500 for a server error. You can also have 403 for a forbidden access... It depends of the case you want to treat. You can see the wikipedia page for a view of the possibilities.
Instead of sending a 'success':False use this :
response = JsonResponse({"error": "there was an error"})
response.status_code = 403 # To announce that the user isn't allowed to publish
return response
With this jQuery will recognize the answer as an error and you will be able to manage the error type.
To manage your errors in JavaScript :
$("#form").on("submit", function(){
$.ajax({
url: "url",
data: ("#form").serialize,
success: function(data){
alert(data.message);
},
error: function(data){
alert(data.status); // the status code
alert(data.responseJSON.error); // the message
}
});
Try this. I think there is a syntax error in your code. Also, it will be better if you post your error message. I changed the false to False
Also did you omit your form instance in your code.
def test(request):
if request.method == "POST":
form = MyForm(request.POST)
if form.is_valid():
form.save()
return JsonResponse({"message":"Successfully published"})
else:
'''here i would like to return error something like:'''
return JsonResponse({"success": False, "error": "there was an error"})
else:
return JsonResponse({"success}: False, "error": "Request method is not post"})
Here is my solution. I rewrote your code:
def test(request):
if request.method == "POST":
if form.is_valid():
form.save()
return JsonResponse({"message":"Successfully published"}, status=200)
else:
return JsonResponse({"error": "there was an error"}, status=403)
else:
return JsonResponse({"error": "Request method is not post"}, status=403)
$(document).on("submit","#form", function(){
$.ajax({
url: "url",
data: ("#form").serialize,
success: function(data){
alert(data.message);
},
error: function(data){
alert(data.responseJSON.error);
}
});

django ajax call return 403 bad request

I'm trying to compile project https://github.com/kannan4k/django-carpool
please refer this project repo for this issue.
and end up with following error during ajax call.
Failed to load resource: the server responded with a status of 400 (BAD REQUEST).
I know this is because of ajax post request & CSRF tokens.
following is my setting.
1. disable "django.middleware.csrf.CsrfViewMiddleware"
2. in new_trip page I have a button (Postdata)so this button sends an ajax request.
My View:-
#login_required
def save_journey(request):
if request.is_ajax() and request.method == "POST":
try:
res = json.loads(request.body)
cords = res['cords']
cords = [[x['d'], x['e']] for x in cords]
distance = res['distance']
start_place = res['start']
end_place = res['end']
clusters = clusterize_latlngs(cords, distance)
time = datetime.datetime.strptime(res['time'], "%m/%d/%Y %H:%M")
Trip.objects.create(user=request.user, time=time, cluster=json.dumps(clusters), travel_distance=distance,
start_place=start_place, end_place=end_place)
return HttpResponse()
except:
return HttpResponseBadRequest()
else:
return HttpResponseNotAllowed(['POST'])
Ajax call (home.js)
function postData() {
radius = 0;
var url = "/save_journey/";
var dataType = 'json';
if (type == 'r') {
radius = $('#radius').val();
url = "/get_results/";
dataType = 'html';
}
var data = JSON.stringify({
cords: myroute,
time: document.getElementById('dateStart').value,
start: document.getElementById('startPlace').innerHTML,
end: document.getElementById('endPlace').innerHTML,
radius: radius,
distance: distance
});
$.ajax({
type: "POST",
url: url,
dataType: dataType,
data: data,
success: function (data) {
if (type == 'r') {
window.location.href = "/search_results/";
}
else {
window.location.href = '/trip_success/';
}
},
error: function () {
console.log('Error getting options list...')
}
});
console.log(data);
}
this code is not able to call /save_journey/ URL.
I tried many answers from stack overflow & didn't figure out what is the problem .
You should never disable csrftoken unless you're absolutely sure about what you're doing. It's an important part of the security features implemented in Django.
Here is an example of how you can use Ajax with Django with csrftoken:
You can use Ajax Post to send JSON to Django and then handle the arguments as a dict(). Here is an example:
In browser (JQuery/JavaScript):
function newModule() {
var my_data = $("#my_element").val(); // Whatever value you want to be sent.
$.ajax({
url: "{% url 'modules' %}", // Handler as defined in Django URLs.
type: "POST", // Method.
dataType: "json", // Format as JSON (Default).
data: {
path: my_data, // Dictionary key (JSON).
csrfmiddlewaretoken:
'{{ csrf_token }}' // Unique key.
},
success: function (json) {
// On success do this.
},
error: function (xhr, errmsg, err) {
// On failure do this.
}
});
In server engine (Python):
def handle(request):
# Post request containing the key.
if request.method == 'POST' and 'my_data' in request.POST.keys():
# Retrieving the value.
my_data = request.POST['my_data']
# ...
Hope this helps.

Django : send form in ajax with files

I know, i know, there are already some questions on this subject and believe my i've tried many many thing but still, i can't make it work.
I had a page with the form, tu upload an img with a comment (so a textarea and a file input). The thing is, i don't want to have a specific page for this form, so i have a popin with the form in a page. So i decided to do it in ajax (so the user can stay on the page and upload severals photos).
But I keep having a mistake, 'the comment field is required'. It looks like the form sent is empty. Following documentation and many (MANY) advices this is how i did it :
Form.py
class UploadPhotoForm(ModelForm):
class Meta:
model = Photo
fields = ['picture', 'comment']
def __init__(self, *args, **kwargs):
self.request = kwargs.pop("request", None)
super(UploadPhotoForm, self).__init__(*args, **kwargs)
def save(self):
photo = super(UploadPhotoForm, self).save(commit=False)
artist = Artists.objects.get(user=self.request.user)
photo.artist = artist
photo.save()
return photo
views.py (the one handling the form : i changed it when i wanted to make ajax):
#login_required
#require_POST
def upload_photo_artist(request):
form = UploadPhotoForm(request.POST, request.FILES, request=request)
if form.is_valid():
form.clean()
form.save()
response = {
'code': 1,
'message': 'success',
}
return HttpResponse(
json.dumps(response),
content_type='application/json'
)
else:
response = form.errors.as_json()
return HttpResponse(
json.dumps(response),
content_type='application/json'
)
And the JS part :
$('#upload_photo').submit(function(e){
e.preventDefault();
var csrftoken = getCookie('csrftoken');
var data = new FormData($(this)[0]);
data.append('csrfmiddlewaretoken', csrftoken);
//data.append('comment', $(this).find('div.input-field').find('textarea').val());
//data.append('photo', $(this).find('div.file-field').find('input:file')[0]);
$.ajax({
url: "/photo/upload",
type: "POST",
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
data: data,
processData: false,
contentTYpe: false,
success: function(data) {
if(data['code']== 1) {
location.reload();
}
else {
alert(data);
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
So it looks like the formData object send is just an empty thing, but i've read the documentation and some examples and i don't see what am I doing wrong here.
You can see in comment the append() method of FormData object. I've tried to just declare a new FormData object empty and add then the fields.
In last try, i had directly the CSRFToken in the FormData object, but still, doesn't work.
If someone can help, that'd be great !

access the error block in ajax request even the reponse is 200 ok

i am doing dross domain request from ajax. the request seems to be ok and it is hiting database successfuly and returning 200 ok response but in client side still it is going in failure block.
this is my code.
validate($(".confpassword").val(),$("#psw").val());
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
var email = $("#email").val();
var password = $("#psw").val();
var birthday = $("#birthday").val();
var sendInfo = {
firstname: firstname,
lastname: lastname,
email: email,
password: password,
birthday: birthday
};
$.ajax({
type: 'POST',
url: 'http://localhost:3001/users/create',
data: JSON.sendInfo,
crossDomain: true,
dataType: 'application/json; charset=utf-8',
success: function (data) {
alert('success.............');
},
error: function(){
alert('failure............');
}
});
if somebody knows please help me
this is my server side response in ruby:
def create
#user=User.create(:birthday=> params[:birthday],:email=> params[:email],:firstname=> params[:firstname], :lastname=> params[:lastname],:password=>params[:password])
respond_to do |format|
if #user.save
format.json { render :json => #user,:status=>200}
else
format.json { render :json => #user.errors, :status => :unprocessable_entity}
end
end
end
Since browser doesnot allow cross-domain server calls we can do that by configuring apache as a proxy to interact with target server
Here is the solution.
Add a "Location" tag in http.conf file of local apache server. Then your server will act as proxy and redirect your calls to target server.
Example:
ProxyPass abc dot come
ProxyPassReverse abc dot com
All calls to <> will be redirected to abc dot com
Hope this would be helpful to you.
Not sure how JSON.sendInfo works, but in JSONP you need to return a callback from the url and pass it back into the response, like this:
format.jsonp { render json: results, callback: params[:callback]}

Categories