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.
Related
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
View.py
def export(request):
if request.is_ajax():
ourid = request.GET.getlist("terid")
Case_Detail = Case_Info_Resource()
for i in ourid:
print(i)
queryset = Case_Info.objects.filter(id=i)
dataset = Case_Detail.export(queryset)
response = HttpResponse(
dataset.xls, content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename="persons.xls"'
print("breakpoint")
return response
Ajax Script
<script>
$(document).ready(function () {
$('#Download').click(function () {
var list = [];
$("input:checkbox[name='checkbox']:checked").each(function () {
list.push($(this).val());
});
$.ajax({
url: '/Account_Manager/Download/',
type: 'GET',
data: { 'terid': list },
traditional: true,
dataType: 'html',
success: function () {
alert("The best cricketers are: " + list.join(", "));
}
});
});
});
</script>
Error:
The view Apps.views.export didn't return an HttpResponse object. It returned None instead.
So, Ajax wants us to return the value in HttpResponse but I need to pass the response normally in order to download the excel which I am creating. I think I checked all the possible answers and struggling with it from the last 3 days. Thank you in advance for any help, suggestions, or edit.
I am running a python REST server, using Flask, to create a website. On the website, I have a number of buttons that call various 3rd party APIs, using AJAX, and get the information back.
The APIs work, and I can get the information back (confirmed that it is accurate using console.log). However, I can't figure out how, or where to pass the information from the AJAX to the server, so that I can process it.
My HTML/JS code is:
<script>
function Enquiry() {
var selection = document.getElementById("Selection").value
// Get values for API
var n = selection.indexOf(" ");
var symbol = selection.substring(0,n)
var API_URL = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=" + symbol + "&apikey=XXX"
// AJAX to API
$.ajax({
url: API_URL,
method: "GET",
data: "",
dataType: "JSON",
success: function(result){
console.log(result)
},
error: function(xhr,status,error){
console.log("error: "+status+" msg:"+error);
}
});
}
</script>
And my Flask script is:
#app.route("/")
def home():
return render_template(Stocks.html)
#app.route("/Stocks")
def getAll():
results = stocksDAO.getAll()
return jsonify(results)
#app.route("/Stocks/<int:id>")
def getById(id):
sel_stock = stocksDAO.findById(id)
return jsonify(sel_stock)
#app.route("/Stocks", methods=["POST"])
def create():
if not request.json:
abort(400)
stock = {
"Stock": request.json["Stock"],
"Name": request.json["Name"],
"Price": request.json["Price"],
}
values = (stock["Stock"], stock["Name"], stock["Price"])
newId = stocksDAO.create(values)
stock["ID"] = newId
return jsonify(stock)
I need to validate, on server side, if a person with a given registration number is already on the database. If this person is already registered, then I proceed with the program flow normally. But, if the number is not already registered, then I'd like to show a confirmation dialog asking if the operator wants to register a new person with the number entered and, if the operator answers yes, then the person will be registered with the number informed on the form on it's submission.
I've tried
Server side(PHP):
if (!$exists_person) {
$resp['success'] = false;
$resp['msg'] = 'Do you want to register a new person?';
echo json_encode($resp);
}
Client side:
function submit(){
var data = $('#myForm').serialize();
$.ajax({
type: 'POST'
,dataType: 'json'
,url: 'myPHP.php'
,async: 'true'
,data: data
,error: function(response){
alert('response');
}
});
return false;
}
I can't even see the alert, that's where I wanted to put my confirmation dialog, with the message written on server side. Other problem, how do I resubmit the entire form appended with the operator's answer, so the server can check if the answer was yes to register this new person?
EDIT
I was able to solve the problem this way:
Server side(PHP):
$person = find($_POST['regNo']);
if ($_POST['register_new'] === 'false' && !$person) {
$resp['exists'] = false;
$resp['msg'] = 'Do you want to register a new person?';
die(json_encode($resp)); //send response to AJAX request on the client side
} else if ($_POST['register_new'] === 'true' && !$person) {
//register new person
$person = find($_POST['regNo']);
}
if($person){
//proceed normal program flow
}
Client side:
function submit(e) {
e.preventDefault();
var data = $('#myForm').serialize();
var ajax1 = $.ajax({
type: 'POST'
, dataType: 'json'
, async: 'true'
, url: 'myPHP.php'
, data: data
, success: function (response) {
if (!response.exists && confirm(response.msg)) {
document.getElementById('register_new').value = 'true'; //hidden input
dados = $('#myForm').serialize(); //reserialize with new data
var ajax2 = $.ajax({
type: 'POST'
, dataType: 'json'
, async: 'true'
, url: 'myPHP.php'
, data: data
, success: function () {
document.getElementById('register_new').value = 'false';
$('#myForm').unbind('submit').submit();
}
});
} else if (response.success) {
alert(response.msg);
$('#myForm').unbind('submit').submit();
}
}
});
}
There doesn't appear to be anything wrong with your PHP.
The problem is (1) You are doing the alert inside of an error callback, and your request isn't failing, so you don't see the alert. (2) You are alerting the string 'response' instead of the variable response.
It is also worth noting that you should be using the .done() and .fail() promise methods (http://api.jquery.com/jquery.ajax/#jqXHR).
Here is the fixed JS:
function submit() {
var data = $('#myForm').serialize();
// Same as before, with the error callback removed
var myAjaxRequest = $.ajax({
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
});
// The request was successful (200)
myAjaxRequest.done(function(data, textStatus, jqXHR) {
// The data variable will contain your JSON from the server
console.log(data);
// Use a confirmation dialog to ask the user your question
// sent from the server
if (confirm(data.msg)) {
// Perform another AJAX request
}
});
// The request failed (40X)
myAjaxRequest.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
return false;
}
Also, you are setting a 'status' in PHP and checking that in the JS (I presume). What you want to be doing is setting a HTTP status code from the server, as below:
if (!$exists_person)
{
$resp['msg'] = 'Do you want to register a new person?';
// 400 - Bad Request
http_response_code(400);
echo json_enconde($resp);
}
Then, jQuery will determine whether the request failed based on the status code you respond with. 200 is a successful request, and 400 numbers are fail.
Check out this page for a full list: https://httpstatuses.com/
Okay so this is a two part question; I'll try my best to answer both parts:
Part 1: How to detect if success is false and trigger the confirmation popup?
In jQuery.ajax the error handler is triggered based on response code. This is probably not what you want. You can use your success handler and test the value res.success to see if it's true or false. It would be something along the lines of:
function submit(e) {
e.preventDefault();
var data = $('#myForm').serialize();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
}).done(function(res) {
if (!res.success) {
alert(res.msg);
}
});
}
Part 2: How do I resubmit with a confirmation?
Working off of our previous code we will make some changes that allow for submit() to be passed an argument registerNew. If registerNew is true we will pass it as a param to the ajax handler in the PHP so it knows we want to register a new person. The Javascript will look something like this:
function submit(e, registerNew) {
if (e) e.preventDefault();
var data = $('#myForm').serialize();
var ajax_options = {
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
};
ajax_options.data.register_new = !!registerNew;
$.ajax(ajax_options).done(function(res) {
if (!res.success && confirm(res.msg)) {
submit(null, true);
}
});
}
As you can see here, we are passing a new register_new param in the data in our ajax options. Now we need to detect this on the PHP side, which is easy enough and looks like this (this goes in your php ajax handler):
if ($_POST["register_new"]) {
// new user registration code goes here
} else {
// your existing ajax handler code
}
Add confirm inside submit function
function submit(){
var data = $('#myForm').serialize();
if (confirm('Are you ready?')) {
$.ajax({
type: 'POST'
,dataType: 'json'
,url: 'myPHP.php'
,async: 'true'
,data: data
,error: function(response){
alert('response');
}
});
}
return false;
}
I'm trying to get all my posts from the database to be displayed with the help of ajax or getjson but can't get it to work. Using mvc web api and I have a view where I want to display it. There is a method working called post so nothing wrong with my routing etc.
Code for my views js-script, I want to display all posts with the help of my mvc api controller and ajax in a div called #userMessage.
$(document).ready(function() {
$('#btnGetPosts').click(function() {
jQuery.support.cors = true;
var recieverID = $('#RecieverID').val();
$.ajax({
url: "/api/Posts/GetPosts" ,
//data: (?)
type: "GET",
dataType: "jsonp",
error: function(request, status, error) {
alert(request.responseText);
},
success: function(data) {
alert(data);
}
});
});
});
my controller method to get all the posts
// GET: api/Posts
public IEnumerable<Post> GetPosts()
{
//querystring is made to get the recieverID, it's also reachable in the view. //("#RecieverID")
string querystring = HttpContext.Current.Request.QueryString["Username"];
// Converts Username querystring to a user-id
int id = UserRepository.GetUserId(querystring);
// uses linq to get a specific user post (all posts)
var userPost = PostRepository.GetSpecificUserPosts(id);
return userPost;
}
my PostRepository.GetSpecifiedUserPosts method in my repository
public List<Post> GetSpecificUserPosts(int user)
{
using (var context = new DejtingEntities())
{
var result = context.Posts
.Where(x => x.RecieverID == user)
.OrderByDescending(x => x.Date)
.ToList();
return result;
}
Try this
$(document).ready(function() {
$('#btnGetPosts').click(function() {
jQuery.support.cors = true;
var recieverID = $('#RecieverID').val();
$.ajax({
url: "/api/Posts/Posts" ,
data: {
username: recieverID
},
type: "GET",
dataType: "jsonp",
error: function(request, status, error) {
alert(request.responseText);
},
success: function(data) {
alert(data);
}
});
});
});
and in code behind,
public IEnumerable<Post> GetPosts(string username)
{
// Converts Username querystring to a user-id
int id = UserRepository.GetUserId(username);
// uses linq to get a specific user post (all posts)
var userPost = PostRepository.GetSpecificUserPosts(id);
return userPost;
}
You use wrong url. Try send ajax request to '/api/Posts'.
Also you can add routing attribute to the action [Route('/api/Posts/GetPosts')] and send request to '/api/Posts/GetPosts'.
See Calling the Web API with Javascript and jQuery and Routing in ASP.NET Web API.