Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

233
Views
syntax error when using search in Javascript

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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;
about 4 years ago · Juan Pablo Isaza Report

0

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`
    })
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!