• 42
Votes
name

A PHP Error was encountered

Severity: Notice

Message: Undefined index: userid

Filename: views/question.php

Line Number: 191

Backtrace:

File: /var/www/html/cnasolution/site/application/views/question.php
Line: 191
Function: _error_handler

File: /var/www/html/cnasolution/site/application/controllers/Questions.php
Line: 419
Function: view

File: /var/www/html/cnasolution/site/index.php
Line: 315
Function: require_once

name Punditsdkoslkdosdkoskdo

send data to ajax from node server

i need to check if a token entred by user exist ,

my node js controller :

const checktoken = async (req, res) => {     const token = req.body.token      User.findOne({'token': token }).then((user) => {         if (user) {             return res.end("GOOOOD");         }         return res.end("Baad");     })     .catch((err) => console.log(err))    } 

Ajax side :

$(document).ready(function(){     $('#form').submit(function (e) {         // e.preventDefault()          $.ajax({             type: 'POST',         url: '/api/token/'         })         .done(function(data) {             alert(data)         })         .fail(function(xhr, status, error) {             console.log("Errrrrrr       " + error);         })         .always(function(data){         });     }) }) 

html form :

the problem is i got always an alert (BAD token) whenever is good or not and then another page is printed with good result in text format

exemple if i put good token : Alert is Bad token then another page printed : good token (this means result from node is ok) the problem with AJAX

Download script demo [LINK] [Origin]
Download script demo [LINK 2] [Onedrive] Download script demo [LINK 2] [Google drive]

First of all, you are double submitting because your form will submit while your ajax call will also fire. Change the action on the form to ensure that it won't try to post on its own (alternatively, you can uncomment e.preventDefault in your submit handler). Also, you aren't including any data in your ajax call:

$(document).ready(function(){     $('#form').submit(function (e) {     // e.preventDefault()          $.ajax({             type: 'POST',             contentType: 'application/json',             url: '/api/token/',             data: JSON.stringify({ token: $('#token').val() })         })         .done(function(data) {             alert(data)         })         .fail(function(xhr, status, error) {             console.log("Errrrrrr       " + error);         })         .always(function(data){         });     }) }) 

You haven't included your Express setup code, but this will require the line app.use(Express.json()) or (express.json() depending on what you named the import) in order to parse the body from JSON into an object

see demo
  • 19
Reply Report