Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

234
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda