Bad request in Flask - python

When I request something to python by AJAX, everything runs OK in python, but, when the route return my informations for AJAX, simply he create another blank page with the text that I returned, and not did what I want in the page who needs to be.
Here the response image
image2
Here is the code:
#app.route('/', methods=['POST', 'GET'])
def bot():
texto = request.form['text']
print(texto)
conversation = ConversationV1(
username='a33eb2c9-d218-4e05-a8ff-a46b59c5c3b1',
password='VATP3XEHsrPL',
version='2017-05-26'
)
context = {}
workspace_id = '96cbce3b-2fd3-49b0-ad57-da62c33547ee'
user = texto
response = conversation.message(
workspace_id=workspace_id,
message_input={'text': user},
context=context
)
context = response['context']
#se há intenções e dialogo
if response['intents'] or response['entities']:
if response['intents']:
intent = (json.dumps(response['intents'][0]['intent'],indent = 2))
intent = intent[1:-1]
dialog = (json.dumps(response['output']['nodes_visited'][0],indent = 2))
dialog = dialog[1:-1]
#se há resesposta à intenção
if response['output']['text']:
resposta = json.dumps(response['output']['text'][0],sort_keys=True, indent=4)
resposta = resposta[1:-1]
resposta = resposta.encode('utf-8')
resp = (resposta.decode('unicode-escape'))
#se entrou no nó x,y,z
if dialog == "perfil_e_id":
ID = (json.dumps(response['entities'][0]['value'],indent = 2))
ID = ID[1:-1]
print (ID)
resp = perfill(ID)
elif dialog == "perfil":
return resp
ID = texto
print ("Ikrl : " + ID)
resp = perfil()
elif dialog == "heroi":
ID = (json.dumps(response['entities'][0]['value']))
ID = ID[1:-1]
resp = herostats(int(ID))
return resp
elif dialog == "counterheroi":
ID = (json.dumps(response['entities'][0]['value']))
ID = ID[1:-1]
resp = herostats(int(ID))
return resp
else:
resposta = json.dumps(response['output']['text'][0],sort_keys=True, indent=4)
resposta = resposta[1:-1]
resposta = resposta.encode('utf-8')
resp = (resposta.decode('unicode-escape'))
print (resp)
return resp
And my ajax code:
$(function(){
$(".mytext").on("keyup", function(e){
if (e.which == 13){
var text = $(this).val();
if (text !== ""){
insertChat("me", text);
document.getElementById("nome").innerHTML = text;
$(this).val('');
}
$.ajax({
url: '/',
data: $(text),
type: 'POST',
success: function(response){
console.log(response);
insertChat("you", response)
},
error: function(error){
console.log(error)
}
})
}
});
});
if you need test in your pc, I upload a .rar file
https://drive.google.com/open?id=0B9TVHd_5neJ1amdqZWVrbm9mX2c

You haven't cancelled the default submit action.
if (e.which == 13){
e.preventDefault();
...

Related

Flask,Discord.py requests.exceptions.HTTPError: 400

hi, i am making auth bot with flask and python, when they click on the authorization link, this error comes to the console and there is no authorization
Error coming to console when someone clicks the link
Error:
[2023-02-03 07:29:44,909] ERROR in app: Exception on /discordauth [GET]
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 2073, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1518, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1516, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1502, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "C:\Users\Administrator\Desktop\Discord-baker-main\application.py", line 37, in discord
data = exchange_code(code)
File "C:\Users\Administrator\Desktop\Discord-baker-main\application.py", line 187, in exchange_code
r.raise_for_status()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\models.py", line 943, in raise_for_status
raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 400 Client Error: Bad Request for url: https://discord.com/api/v9/oauth2/token```
When you click on the authorization link, this error appears on the link:
500 Internal Server Error
**Internal Server Error**
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
My code:
import requests
import configparser
import os
from flask import Flask, request, redirect, url_for, render_template
config = configparser.ConfigParser()
config.read('database.ini')
application = Flask(__name__)
API_ENDPOINT = "https://discord.com/api/v9"
#leave this like this
CLIENT_ID = config['apiinfo']['CLIENT_ID']
CLIENT_SECRET = config['apiinfo']['CLIENT_SECRET']
CLIENT_TOKEN = config['botinfo']['bottoken']
DOMAIN = config['apiinfo']['DOMAIN']
exchangepass = config['apiinfo']['exchangepass']
SCOPE = "identify guilds guilds.join"
REDIRECT_URI = f"{DOMAIN}/discordauth"
welcomechannel = str(config['botinfo']['welcome_channel'])
memberrole = str(config['botinfo']['memberrole'])
restorekey = str(config['botinfo']['therestorekey'])
guildid = config['info']['guildid']
def cls():
os.system('cls' if os.name == 'nt' else 'clear')
#application.route('/working', methods=['GET', 'POST'])
def working():
return 'true'
#application.route('/discordauth', methods=['GET', 'POST'])
def discord():
print("In discordauth")
code = request.args.get('code')
data = exchange_code(code)
state = request.args.get('state')
access_token = data.get("access_token")
refresh_token = data.get("refresh_token")
data2 = getid(access_token)
userid = str(data2.get("id"))
username = data2.get("username")
country = data2.get("locale")
if userid in config['useridsincheck']:
config['users'][userid] = 'NA'
config[userid] = {}
config[userid]['refresh_tokens'] = refresh_token
config[userid]['refresh'] = 'true'
config[userid]['country'] = country
with open('database.ini', 'w') as configfile:
config.write(configfile)
if request.method == 'POST':
return 'success'
if request.method == 'GET':
return render_template('Authcomplete.html')
elif userid in config['users']:
if request.method == 'POST':
return 'success'
if request.method == 'GET':
return render_template('Authcomplete.html')
else:
return 'fail'
#application.route('/restore', methods=['GET', 'POST'])
def restore():
password = request.json['code']
if password == exchangepass:
restoreserver()
return 'succsess'
else:
print("Invalid password" + password)
return 'wrong password'
#application.route('/', methods=['GET', 'POST'])
def testbuild():
return render_template('home.html')
def getid(info):
url = "https://discord.com/api/v9/users/#me"
payload={}
accsestokentoget = info
headers = {
'Authorization': 'Bearer ' + accsestokentoget,
}
response = requests.request("GET", url, headers=headers, data=payload)
response.raise_for_status()
return response.json()
#error to fix in here
#application.route('/requestid', methods=['GET', 'POST'])
def requestid():
print("Part requestid")
key = request.json['key']
id = str(request.json['id'])
print(id)
print(key)
if key == exchangepass:
if id in config['users']:
return 'succsess'
else:
print("key was correct")
#check if the category is in the config
config['useridsincheck'] = {}
config['useridsincheck'][id] = 'waiting'
with open('database.ini', 'w') as configfile:
config.write(configfile)
return 'succsess'
else:
print("key was wrong")
return 'wrong key'
#application.route('/data', methods=['GET', 'POST'])
def data():
key = request.json['key']
dataset = request.json['dataset']
print("part data")
if key == config['apiinfo']['tempkey']:
if dataset == 'CLIENT_ID':
return CLIENT_ID
if dataset == 'guildid':
return guildid
if dataset == 'CLIENT_SECRET':
return CLIENT_SECRET
if dataset == 'bottoken':
return CLIENT_TOKEN
if dataset == 'exchangepass':
return exchangepass
if dataset == 'welcomechannel':
return welcomechannel
if dataset == 'verifiedrole':
return memberrole
if dataset == 'restorekey':
return restorekey
if config['apiinfo']['botsetupcomplete'] == 'no':
if dataset == 'pass':
return config['apiinfo']['tempkey']
config['apiinfo']['botsetupcomplete'] = 'yes'
with open('database.ini', 'w') as configfile:
config.write(configfile)
return 'error dataset wrong'
#application.route('/checkifverifydone', methods=['GET', 'POST'])
def checkifverifydone():
print("Part checkifverifydone")
key = request.json['key']
id = str(request.json['id'])
print(id)
print(key)
if key == exchangepass:
print("key was correct")
if id in config['users']:
config['useridsincheck'][id] = 'verified'
with open('database.ini', 'w') as configfile:
config.write(configfile)
print("corect")
return 'true'
else:
print("id was not found")
return 'false'
else:
return 'false'
def exchange_code(code):
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
data = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'authorization_code',
'code': code,
'redirect_uri': REDIRECT_URI,
'scope': SCOPE
}
r = requests.post(
f"{API_ENDPOINT}/oauth2/token",
data=data,
headers=headers
)
r.raise_for_status()
return r.json()
def get_new_token(old_token): # gets new refresh_token
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
data = {
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'grant_type': 'refresh_token',
'refresh_token': old_token
}
r = requests.post(
f"{API_ENDPOINT}/oauth2/token",
data=data,
headers=headers
)
r.raise_for_status()
return r.json()
def add_to_guild(access_token, user_id, guild_id):
headers = {
"Authorization" : f"Bot {CLIENT_TOKEN}",
'Content-Type': 'application/json'
}
data = {
"access_token" : access_token
}
response = requests.put(
url=f"{API_ENDPOINT}/guilds/{guild_id}/members/{user_id}",
headers=headers,
json=data
)
def restoreserver():
userids = config['users']
guildid = config['info']['guildid']
for idsinlist in userids:
print(idsinlist)
code = config[idsinlist]['refresh_tokens']
if config[idsinlist]['refresh'] == "false":
try:
data = exchange_code(code)
access_token = data.get("access_token")
add_to_guild(access_token, idsinlist, guildid)
config[idsinlist]['refresh_tokens'] = data.get("refresh_token")
config[idsinlist]['refresh'] = 'true'
with open('database.ini', 'w') as configfile:
config.write(configfile)
except:
print("error")
if config[idsinlist]['refresh'] == "true":
try:
data = get_new_token(code)
access_token = data.get("access_token")
add_to_guild(access_token, idsinlist, guildid)
config[idsinlist]['refresh_tokens'] = data.get("refresh_token")
with open('database.ini', 'w') as configfile:
config.write(configfile)
except:
print("error")
else:
print("Refresh status is invalid")
print(code)
if __name__ == '__main__':
cls()
application.run(host='0.0.0.0', port=80) #change to your port default port is 80

Staying login problem about CallbackURL after payment

my view is like :
def get_user_pending_order(request):
user_profile = get_object_or_404(Profile, user=request.user)
order = Order.objects.filter(owner=user_profile, is_ordered=False)
if order.exists():
return order[0]
return 0
MERCHANT = 'xxx...xxx'
ZP_API_REQUEST = "https://api.zarinpal.com/pg/v4/payment/request.json"
ZP_API_VERIFY = "https://api.zarinpal.com/pg/v4/payment/verify.json"
ZP_API_STARTPAY = "https://www.zarinpal.com/pg/StartPay/{authority}"
amount = ''
description = "text" # Required
email = 'example#email.com' # Optional
mobile = '09999999999' # Optional
# Important: need to edit for realy server.
CallbackURL = 'https://example.com/payment/verify/'
def send_request(request):
print(get_user_pending_order(request).owner.phone_number)
req_data = {
"merchant_id": MERCHANT,
"amount": int(get_user_pending_order(request).get_total()),
"callback_url": CallbackURL,
"description": description,
"metadata": {"mobile": mobile,
"email": email}
}
req_header = {"accept": "application/json",
"content-type": "application/json'"}
req = requests.post(url=ZP_API_REQUEST, data=json.dumps(
req_data), headers=req_header)
authority = req.json()['data']['authority']
if len(req.json()['errors']) == 0:
return redirect(ZP_API_STARTPAY.format(authority=authority))
else:
e_code = req.json()['errors']['code']
e_message = req.json()['errors']['message']
return HttpResponse(f"Error code: {e_code}, Error Message: {e_message}")
def verify(request):
t_status = request.GET.get('Status')
t_authority = request.GET['Authority']
if request.GET.get('Status') == 'OK':
req_header = {"accept": "application/json",
"content-type": "application/json'"}
req_data = {
"merchant_id": MERCHANT,
"amount": int(get_user_pending_order(request).get_total()),
"authority": t_authority
}
req = requests.post(url=ZP_API_VERIFY, data=json.dumps(req_data), headers=req_header)
if len(req.json()['errors']) == 0:
t_status = req.json()['data']['code']
if t_status == 100:
user = request.user
order_to_purchase = get_user_pending_order(request)
order_to_purchase.is_ordered = True
order_to_purchase.date_ordered=datetime.datetime.now()
order_to_purchase.created_on_time=datetime.datetime.now()
order_to_purchase.save()
order_items = order_to_purchase.items.all()
for order_item in order_items:
order_item.product.quantity = order_item.product.quantity - 1
order_item.product.save()
order_items.update(is_ordered=True, date_ordered=datetime.datetime.now())
subject = 'successful'
c = {
"refid":str(req.json()['data']['ref_id']),
"ref_code":order_to_purchase.ref_code,
"owner":order_to_purchase.owner,
}
email_template_name = "pay/after_pay_confirm_email.html"
email_html = render_to_string(email_template_name, c)
email_from = settings.EMAIL_HOST_USER
send_mail(subject, email_html, email_from, [user.email], html_message=email_html)
ctx = {'message_good':'good'}
return render(request, 'pay/verify.html', ctx)
elif t_status == 101:
...
else:
....
else:
...
else:
...
At first about user, is logged. and about send_request function it work totally fine...so it pass user into Payment gateway and after successful payment it come back to verify function by CallbackURL. to show success page and do order_to_purchase.is_ordered = True ...
for me with my pc, phone, other android phones, ios, windows, linux. and about browsers like chrome Firefox it work correctly and everything is fine.
but some clients tell me they face to 'AnonymousUser' object is not iterable after successful payment and when they back to verify. its kinda like that they logged out by pushing request to payment gateway.
also i made purchase by that account exactly same way and i didn't face to that error. it show is that phone or browser problem that half of my clients faced to that. i have no idea what should i do!!!

How to fix 'This page was not found' in Flask Python?

I'm setting a new server in Flask for an API. And a server to render the frontend in Flask also. Ok, so when i make a request to a determine API route i get this strange response 'This page was not found'. I it really seems to be every thing ok how can i debug this bug? Other Strange thing is that it allways give me status 200 OK. The error is in the route: #app.route('/v1.0/aluno/update/', methods=['POST'])
API SIDE
#app.route('/v1.0/aluno/<int:aluno_id>', methods=['GET'])
def aluno(aluno_id):
if request.method == 'GET':
cur = mysql.connection.cursor()
query = "SELECT NOME, NUMERO, PASSWORD FROM aluno WHERE NUMERO=%s"
cur.execute(query, (aluno_id,))
data = cur.fetchall()
if len(data) <= 0:
return Response(status=404)
else:
aluno = {
'nome': data[0][0],
'numero': data[0][1],
'password': data[0][2]
}
js = json.dumps(aluno)
resp = Response(js, status=200, mimetype='application/json')
resp.headers['Links'] = 'http://127.0.0.1/aluno'
return resp
#app.route('/v1.0/aluno/delete/<int:aluno_id>', methods=['POST'])
def aluno_delete(aluno_id):
if request.method == 'POST' and request.form['_method'] == 'delete':
query = "DELETE FROM aluno WHERE NUMERO = %s"
cur = mysql.connection.cursor()
cur.execute(query, (aluno_id,))
mysql.connection.commit()
cur.fetchall()
cur.close()
return Response(status=200)
#app.route('/v1.0/aluno/update/<int:aluno_id>', methods=['POST'])
def aluno_update(aluno_id):
form = AlunoForm(request.form)
if request.method == 'POST' and form.validate():
nome = request.form["nome"]
numero = request.form["numero"]
password = request.form["password"]
cur = mysql.connection.cursor()
query = "UPDATE aluno SET NOME=%s, NUMERO=%s, PASSWORD=%s WHERE NUMERO = %s"
cur.execute(query, (nome, numero, password, aluno_id))
mysql.connection.commit()
cur.execute(
"SELECT NOME, NUMERO FROM aluno WHERE NUMERO = %s", (aluno_id,))
data = cur.fetchall()
cur.close()
print(" * DATA ")
print(data)
aluno = {
'nome': data[0][0],
'numero': data[0][1]
}
js = json.dumps(aluno)
resp = Response(js, status=200, mimetype='application/json')
resp.headers['Links'] = 'http://127.0.0.1/aluno'
return resp
elif request.method == 'POST' and not form.validate():
resp = Response(status=400)
resp.headers['Links'] = 'http://127.0.0.1/aluno'
return resp
FRONT-END SIDE
{% endblock %}
<script type="text/javascript" src="{{url_for('static', filename='js/jquery-3.2.1.min.js') }}"></script>
<script type="text/javascript" src="{{url_for('static', filename = 'js/bootstrap.min.js')}}"></script>
<script>
function aluno_update(){
try{
let formElement = document.getElementById("aluno_update")
//let formData = formElement.
//console.log(formData)
$.ajax({
type: "POST",
url: "http://127.0.0.1:80/v1.0/aluno/update/{{aluno['numero']}}",
data: {'nome': 'João Luis','numero':'16172','password':'Password'},
//dataType: 'json',
success: function(data){
//location.href = "http://127.0.0.1:3000/v1.0/alunos/"
alert(data)
console.log(data)
},
error(jqXHR,JQueryXHR,errorThrown){
//console.log(formData)
alert(jqXHR)
alert(JQueryXHR)
alert(errorThrown)
console.log(jqXHR)
console.log(JQueryXHR)
console.log(errorThrown)
}
})
}catch(err){
alert(err)
}
}
</script>
I have tried using POSTMAN instead of the regular web browser. To make the request to the API. But i get the same response: 'This page was not found'
At least i was expecting some sort of 400 Bad Request or something like that.
https://github.com/joaogracio/SqlParser
Form validation fails and you get 400 according to the code below
elif request.method == 'POST' and not form.validate():
resp = Response(status=400)
resp.headers['Links'] = 'http://127.0.0.1/aluno'
return resp

Auto download not working for Django FileResponse

I need to let the Django auto download the generated file.
Tried all different solutions online, none of them works.
Views.py
def validate(request):
if request.method == 'POST':
filename = request.POST.get('source_file')
file_path = os.path.join(settings.MEDIA_ROOT, 'SourceFiles', filename)
region = request.POST.get('region')
product_type = request.POST.get('product_type')
result = validateSource.delay(file_path, region, product_type)
output_filepath, log_filepath = result.get()
if os.path.exists(output_filepath) and os.path.exists(log_filepath):
zip_filename = zipFiles([output_filepath, log_filepath], filename)
zip_filepath = os.path.join(settings.MEDIA_ROOT, zip_filename)
response = FileResponse(open(zip_filepath, 'rb'), as_attachment=True)
return response
raise Http404
Template: code for the form POST.
$(document).on('submit', '#productForm', function(e){
e.preventDefault();
var inputFilePath = document.getElementById('sourceFileInput').files.item(0).name;
$.ajax({
method: 'POST',
url: 'validate/',
data: {
source_file: inputFilePath,
region: $("#Region-choice").val(),
product_type: $("#Product-type").val()}
})
.done(function(){
document.getElementById('lblStatus').innerHTML = "Result: <br/>"
document.getElementById('lblStatusContent').innerHTML = "Success!"
})
.fail(function(req, textStatus, errorThrown) {
document.getElementById('lblStatus').innerHTML = "Result: <br/>"
alert("Something went wrong!:" + textStatus + ' ' + errorThrown )
});
});
});
It's not possible to download files to your computer via an ajax (XHR) request. So you need to redirect the user actually (setting window.location) to a view that downloads the file. Or you can add as a result of the successful POST a button the current page so the user can download the file. In any case, you need to move the file download to a different view so a standard GET request can fetch it.
But your code to return the file in Django (using FileResponse) is correct.
There's also an explanation with an alternative way of doing it here
def validate(request):
if request.method == 'POST':
filename = request.POST.get('source_file')
file_path = os.path.join(settings.MEDIA_ROOT, 'SourceFiles', filename)
region = request.POST.get('region')
product_type = request.POST.get('product_type')
result = validateSource.delay(file_path, region, product_type)
output_filepath, log_filepath = result.get()
if os.path.exists(output_filepath) and os.path.exists(log_filepath):
zip_filename = zipFiles([output_filepath, log_filepath], filename)
zip_filepath = os.path.join(settings.MEDIA_ROOT, zip_filename)
with open(zip_filepath, 'rb') as fh:
response = HttpResponse(fh.read(), content_type="application/force-download")
response['Content-Disposition'] = 'attachment; filename=' + os.path.basename(zip_filepath)
return response
raise Http404

Post 400 (BAD REQUEST)

I'm attempting to submit my form, but it continually fails as there's something wrong with the POST. I'm unsure where/what exactly is causing the server to not process the request whether it's related to syntax, request routing, etc. I've also commented out every line related to file uploads, as well as comment out the if (validated) statement. There are no errors in the console as a result of this, but the form submission still fails. I'd appreciate any help/direction thanks.
I get this error message when I submit the form:
POST http://127.0.0.1:5051/register/ 400 (BAD REQUEST)
views.py
#blueprint.route("register/", methods=['GET', 'POST'])
def register():
"""Renders register page."""
form = RegisterForm()
if request.method == 'POST':
if not form.validate_on_submit():
return render_template('main/register.html', page_title="Service Registration",
form=form, form_success=False, media_types=current_app.config["ACCEPTED_"
"MEDIA_TYPE"])
ticket, err = create_ticket2(customer_id, organization + "\n" + venue_name + "\n" + street + "\n" + country + "\n" + teamviewquestion + "\n" + teamviewerid + "\n" + deviations + "\n" + deviationsnotes + "\n" + displaydirector + "\n" + composer + "\n" + decryptor + "\n" + motionrocket + "\n" + othersoftware,
location=location)
if err:
return render_template('main/register.html', page_title="Service Registration",
form=form, form_success=False, message=err, media_types=current_app.config["ACCEPTED_"
"MEDIA_TYPE"])
else:
success_msg = "Error"
.format(ticket.get('id'))
return render_template('main/register.html', page_title="Service Registration",
form=form, form_success=True, message=success_msg, media_types=current_app.config["ACCEPTED_"
"MEDIA_TYPE"])
return render_template('main/register.html', page_title="Service Registration",
form=form, media_types=current_app.config["ACCEPTED_"
"MEDIA_TYPE"])
"""Handles file upload POSTs."""
first_name = request.form.get("first_name")
last_name = request.form.get("last_name")
name = request.form.get("first_name") + " " + request.form.get("last_name")
email = request.form.get("email")
filename = request.form.get("filename")
file_type = request.form.get("file_type")
if filename == '':
response = make_response("No selected file")
return response, 400
if check_file_type(file_type):
filename = clean_filename(filename)
filename = secure_filename(filename)
filename = unique_filename(filename)
response = generate_presigned_post(filename, file_type)
# CREATE DB REFERENCE
url = "http://nevcodocs.s3.amazonaws.com/Uploads/{}".format(filename)
instance = CustomerFileUpload.query.filter_by(url=url).first()
if not instance:
instance = CustomerFileUpload(url=url, email=email, name=name)
db.session.add(instance)
db.session.commit()
else:
instance.update(created_at=datetime.utcnow())
return response, 200
js (ticket submission function)
$('#ticket-form').submit(function(event) {
if (validated) {
$('#filename').val($('#upload').val());
$.ajax({
type: 'POST',
url: '/register/',
data: $('#ticket-form').serialize()
}).done(function(data) {
var formData = new FormData();
for (var key in data.data) {
formData.append(key, data.data[key]);
}
formData.append('file', $('#upload').prop('files')[0]);
formData.append('csrf_token', '{{ csrf_token }}');
var req = new XMLHttpRequest();
req.onload = function() {
showSpinner(false);
$('#ticket-form').removeClass("support-form-show");
$('#ticket-form').addClass("support-form-hide");
};
req.onerror = function() {
showSpinner(false);
$('#ticket-form-failed').removeClass("support-form-hide");
$('#ticket-form-failed').addClass("support-form-show");
};
req.open('POST', '/register/');
req.send(formData);
}).fail(function(err) {
showSpinner(false);
$('#ticket-form-failed').removeClass("support-form-hide");
$('#ticket-form-failed').addClass("support-form-show");
});
} else {
showSpinner(false);
enableSubmit(true);
}
});
Usually, bad request means that you're trying to fetch data from request object using invalid keys. So you need to make sure that your POST request body (that was sent by javascript) contains all keys which you're using as arguments of request.form.get() method: first_name, last_name, etc...

Categories

Resources