-1

I have tried for hours to get the value from my function after validation but it just does not seem to work. I have tried looking at similar threads but still did not manage to understand their answers. This is my code.

/*$("#submit").click(function(){
    // Set form variable
    var form = $('#loginform');           

    form.submit(function(event){              
      var userid = $('#userID').trim(userid); 
      var password = $('#Password').trim(password); 
        // Process AJAX request
        var validate = $.post('http://localhost:3000/api/login',
               $("loginform").serialize(), function(data){
                   alert(data);
        });

      // Prevent default form action
      event.preventDefault();
    });
}); */
function ajaxcall(url, data, callback) {
$.ajax({
    "url": "http://localhost:3000/api/login", // server url
    "type": 'POST', //POST or GET 
    "data": "#loginform", // data to send in ajax format or querystring format
    "datatype": 'json',
    "beforeSend": function() {
        alert('sending data');
         // do some loading options
    },
    success: function(data) {
        if(data=="Login Success"){
            callback(true); // return data in callback
        } else {
            callback(false);
    }},

    complete: function() {
        alert('ajax call complete');
        // success alerts
    },

    error: function(xhr, status, error) {
        alert(xhr.responseText); // error occur 
    }

});
}

The first part which is commented is basically what I have tried and also failed for me so I decided to use $.ajax instead but it seems like there is no change. This is my html code.

<form method="POST" action="index.html" id="loginform" onsubmit="return ajaxcall(callback)" >

I am looking for some code for me to refer to as a reference or a simple explaination etc. I have looked at this before and tried but it is not working so I am guessing it has to do with my code itself rather than html. Do forgive me for asking the same question but I am pretty much stuck after reading through this thread for hours trying to understand.

How do I return the response from an asynchronous call?

Server code:

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/myproject';

var authenticate = function(db, req, callback){
var cursor = db.collection('LoginID').find({"_id" : req.body.userID, 
"Password" : req.body.Password
}).count(function(err,doc){
        if(err) return callback(err);
        if(doc == 0){
            console.log('Invalid Login ID or Password');
            return callback(null, doc);
        } else {
            console.log('Login Success');
            return callback(null, doc);
        }
    });
}
module.exports = {
postCollection : function(req,res){
    var username = req.body.userID;
    var Password = req.body.Password;
    //var createdDate =  "<b>" + day + "/" + month + "/" + year + "</b>"
    MongoClient.connect(url, function(err, db) {
        //assert.equal(null, err);
        if(err) {
            res.send(err);
            res.end();
        }
        authenticate(db, req, function(err,doc) {
            if(err)
                res.send(err);
            else{
                    if(!doc){
                        res.send( 'Invalid Login ID or Password' );
                        res.end();
                    } else {
                        res.send("Login success")
                        res.end();
                    }
                }
            db.close();
        });
    });
}   
}   

PS: This is for calling my api which then checks the database for the entry of the user and if it is not there it outputs a response "Invalid Login ID or password" and stays on the same page but if there is an entry of the user, it would then output"Login Success" which would then be redirected to index.html. Sorry if I was unclear.

Ong Kong Tat
  • 1,172
  • 2
  • 9
  • 22
  • Please post your relevant server code – Black Jun 12 '17 at 08:38
  • 1
    @Black Edited it with server code – Ong Kong Tat Jun 12 '17 at 08:40
  • What that thread says super briefly is that you absolutely *can't* return a value from and asynchronous function and you actually should not. Basically, you should continue doing what you want with that value in that same callback you defined to get it. Try googling "javascript what is async function". – Kirill Rogovoy Jun 12 '17 at 08:43
  • 1
    `onsubmit="return ajaxcall(callback)"` so from what I see in your code the `callback` is undefined.. More over what is the error ? – Rajshekar Reddy Jun 12 '17 at 08:43
  • @KirillRogovoy thats incorrect, of course you can receive data from aynchronous calls, you will get the response in the function defined in `success` – Black Jun 12 '17 at 08:46
  • @Black what I meant is that you cannot **return** it from that `success` function to the outer scope. Of course, you can access it inside that function. – Kirill Rogovoy Jun 12 '17 at 08:50
  • @KirillRogovoy, you can if you are using callback functions – Black Jun 12 '17 at 08:51
  • Ok, you clearly don't see what I mean. :) We are speaking about different things. – Kirill Rogovoy Jun 12 '17 at 08:54

2 Answers2

0

I have had similar issues with form submit. Then found this, http://malsup.com/jquery/form/#getting-started.

Take a look at this plugin.

Note: Try returning codes instead of string from server, or parse both as JSON. It is usually the best practice.

itssajan
  • 820
  • 8
  • 24
0

You have to pass a key value pair to the data property

" Object must be Key/Value pairs." http://api.jquery.com/jquery.ajax/

So you have to change data to something like this:

data: {loginform_id: "#loginform"},

You also have to remove the " everywhere from the ajax properties.

e.g. change this:

"url": "http://localhost:3000/api/login", // server url
"type": 'POST', //POST or GET 
"data": "#loginform", // data to send in ajax format or querystring format
"datatype": 'json',
"beforeSend": function() {
    alert('sending data');
     // do some loading options
},

to this:

url: "http://localhost:3000/api/login", // server url
type: 'POST', //POST or GET 
data: {loginform_id: "#loginform"}, // data to send in ajax format or querystring format
datatype: 'json',
beforeSend: function() {
    alert('sending data');
     // do some loading options
},
Black
  • 18,150
  • 39
  • 158
  • 271
  • And check your server code, because your function "callback" is undefined – Black Jun 12 '17 at 08:47
  • Hi my server code works normally on postman so I was wondering which one is undefined do you mean my server code or the js code? – Ong Kong Tat Jun 12 '17 at 08:58
  • Both seem to be undefined. Or did you not post the full code? – Black Jun 12 '17 at 08:59
  • In the js code, I thought `callback(true)` is defined and `callback(false)`as well if it is a wrong username or password as for the server code, I did not use the callback for `res.send()` in server code so would that cause problems or not a must? – Ong Kong Tat Jun 12 '17 at 09:04
  • You first have to define the function `callback` before you use it. What output do you get if you execute `console.log(callback);` ? – Black Jun 12 '17 at 09:07
  • Do you mean in the html code itself? Sorry if I misunderstood you because my js code has `function ajaxcall(url,data,callback)` If you mean the html code, I did not know there was a need to define it there as well. Do you have an example so that I can understand? Thank you. – Ong Kong Tat Jun 12 '17 at 09:11
  • In `ajaxcall(url,data,callback)` you are passing the function `callback` to the function `ajaxcall`. But you never defined the function `callback`, it simply does not exist. What output do you get if you call `console.log(callback);` in the `beforeSend` function? – Black Jun 12 '17 at 09:14
  • Do you know of a solution for this because I really did not know that I had to declare the `callback` function which caused my code to not output as expected. – Ong Kong Tat Jun 12 '17 at 09:17
  • You first have to answer my question please, what does `console.log(callback);` return ? – Black Jun 12 '17 at 09:19
  • It returns true or false according to the input that was entered which would then redirect the user to a new page if it is true but if it is false it does not redirect the page and displays "Incorrect Username or Password". – Ong Kong Tat Jun 12 '17 at 09:23
  • No... execute the this code --> `console.log(callback);`<-- and tell us what output do you get from it. You can see it in the developer console (press F12) – Black Jun 12 '17 at 09:41
  • I don't see anything in the console after executing the code `console.log(callback)`. – Ong Kong Tat Jun 12 '17 at 09:48
  • Switch to the tab "console" – Black Jun 12 '17 at 10:01
  • You have to inform yourselve how to debug code. Where exactly did you call `console.log(callback)`? Can you try to execute it directly ín the console? – Black Jun 12 '17 at 12:18
  • It shows undefined `VM499:1 Uncaught ReferenceError: callback is not defined at :1:13` when console.log(callback) is executed into the console – Ong Kong Tat Jun 12 '17 at 14:15
  • Okay there we go. As you can see your callback function is not defined. So you have to define it in the same js file where you make the ajax request, to solve your problem. Just define a simple function e.g `function callback(status) { alert(status); }` can you try this? – Black Jun 12 '17 at 14:42
  • Hi do I define callback inside `$.ajax({` or outside it? I did try defining callback outside `$.ajax({` according to your code `function callback(status) { alert(status); }` and it shows undefined if I logged in to console. – Ong Kong Tat Jun 13 '17 at 00:37
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/146469/discussion-between-ong-kong-tat-and-black). – Ong Kong Tat Jun 13 '17 at 01:09