Reputation: 39
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 :#
Upvotes: 0
Views: 1834
Reputation: 93541
You forgot : .val()
to send the value of inputs :
data: ({username: $('input[name=username]').val(), password: $('input[name=password]').val() }),
and NOT :
data: ({username: $('input[name=username]'),password: $('input[name=password]')}),
Upvotes: 1
Reputation: 879
If I understand you correctly, you may be using the request method.
To retrieve the data from your node server's data you should use the GET
method when the page completes loading.
To send a request to node when the form is submitted your often will send a request from the client side js to make a persistent change to a database on the node server. Depending on what you would like to achieve, you should use the POST
, PUT
, PATCH
, DELETE
methods.
These methods will typically create, update, update a portion of data set, or remove records or documents from an SQL or NoSQL database available to your node server.
Upvotes: 0
Reputation: 226
Preventdefault is creating issue. You can remove that to run Ajax call
Upvotes: 0
Reputation: 6378
Remove the setTimeout which is preventing your preventDefault from running in the actual event handler and causing you to see the response in the browser load rather than ajax handler, and debug from there.
Upvotes: 1