I'm making a forms in Django and JavaScript
I need to display a form after clicking on a button, which will be answered and it will return (in JSON format) a list with the answers.
My code index.js
document.querySelector("#create-blank-form").addEventListener("click", () => {
const csrf = Cookies.get('csrftoken');
fetch('/form/create', {
method: "POST",
headers: {'X-CSRFToken': csrf},
body: JSON.stringify({
title: "Untitled Form"
})
})
.then(response => response.json())
.then(result => {
window.location = `/form/${result.code}/edit`
})
})
The error, the error points to .then(result...)
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Promise.then (async)
(anonymous)
My views.py
def create_form(request):
print('hi')
# Creator must be authenticated
# Create a blank form API
if request.method == "POST":
print('hi')
data = json.loads(request.body)
title = data["title"]
code = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(30))
choices = Choices(choice = "Option 1")
choices.save()
question = Questions(question_type = "multiple choice", question= "Untitled Question", required= False)
question.save()
question.choices.add(choices)
question.save()
form = Form(code = code, title = title, creator=request.user)
form.save()
form.questions.add(question)
form.save()
return JsonResponse({"message": "Sucess", "code": code})
My .html
<div class="form-template-box">
<img src = "{% static 'Icon/blank-form.png' %}" alt = "Blank form" title = "Blank form" id="create-blank-form">
<span class="form-template-label">Blank Form</span>
</div>
my urls.py
path('form/create', views.create_form, name="create_form"),
EDIT
my problem was with the url, in urls.py, another part of my code was for some reason influencing in a bad way. thanks for the comments, they helped me find the error
The error SyntaxError: Unexpected token < in JSON at position 0 says that the first character of the response is '<' and suggests that the response given is in XML format rather than JSON.
So response.json() wont work becuase response is not valid JSON. if it were, the first character would be '{' or '['.
I would suggest you console.log() the response to check the format of it and then extract the 'code' element youre looking for using:
const parser = new DOMParser();
const doc = parser.parseFromString(response, 'text/xml');
const codeYouWant = doc.getElementsByTagName("code")[0].innerHTML;
I think your function has some problems that return an error instead of JSON Response. So in .then(response => response.json()) will raise error. You can try the sample below to check the error.
if request.method == "POST":
try:
print('hi')
data = json.loads(request.body)
title = data["title"]
code = ''.join(random.choice(string.ascii_letters + string.digits) for x in range(30))
choices = Choices(choice = "Option 1")
choices.save()
question = Questions(question_type = "multiple choice", question= "Untitled Question", required= False)
question.save()
question.choices.add(choices)
question.save()
form = Form(code = code, title = title, creator=request.user)
form.save()
form.questions.add(question)
form.save()
return JsonResponse({"message": "Sucess", "code": code})
except Exception as err:
return JsonResponse({"message": "Failed", "error": err})
And
.then(result => {
console.log("DEBUG result: ", result);
window.location = `/form/${result.code}/edit`
})
my problem was with the url, in urls.py, another part of my code was for some reason influencing in a bad way. thanks for the comments, they helped me find the error