Im trying to send data from my server side to my client side with ajax but when i use res.send(data) in node, it show me a empty html with the data and i want to get data from my client side without reloading the page and edit something in my actual html
Here's my server-side code
app.post('/',(req,res)=>{
var userName = req.body.username;
var password = req.body.password;
connection.query('SELECT * from admin',(err, rows, fields)=> {
if (!err){
if((userName == rows[0].usuario) && (password == rows[0].contraseña)){
res.sendStatus(200);
}else{
res.send('Incorrect username or password')
}
}else{
res.send('Error while performing Query.');
}
});
});
Here's my client-side code
$(document).ready(function(){
$('#login-form').submit(function (e) {
setTimeout(function () {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/',
dataType: 'jsonp',
data: ({username: $('input[name=username]'),password: $('input[name=password]')}),
success: function(data,textStatus){
if(textStatus.statusCode == 200) {
$('.error-user').html('Succes');
}else{
$('.error-user').html('Not Success');
}
},
});
}, 1000);
});
});
UPDATE: I removed the setTimeOut() but when I submit the form the page freeze like two seconds and then nothing happen, I get this 'error Maximum call stack size exceeded', dont get me data just stay in the same view if like post method was never called
UPDATE-FINAL: I got values from input outside of the ajax and it works nice,thanks :#
setTimeout()? It is part of the problem. Your form has submitted and the page reloaded from the form submission BEFORE you run your ajax call and before you calle.preventDefauilt()so that is called too late. Remove thesetTimeout()or put thee.preventDefault()before thesetTimeout(). In either case, thesetTimeout()seems like screwy code. If you thought you were fixing something with that, then that's a hack and you should fix whatever it is the proper way and remove thesetTimeout().