Help, I'm Stuck! I am playing with a CRUD setup with Node Express but with AJAX post request. I have the read form working fine.
The form has one input filed which is a lookup email. AJAX post the form data with the following code
if ($("#rsvp-search-form").length) {
$("#rsvp-search-form").validate({
rules: {
...
},
messages: {
...
},
submitHandler: function (form) {
$("#loader").css("display", "inline-block");
$.ajax({
type: "POST",
url: "/",
data: $(form).serialize(),
success: function (data, textStatus, jqXHR){
if (typeof data.redirect == 'string')
window.location = data.redirect;
}
,
error: function() {
$( "#loader").hide();
$( "#error").slideDown( "slow" );
setTimeout(function() {
$( "#error").slideUp( "slow" );
}, 5000);
}
});
return false; // required to block normal submit since you used ajax
}
});
}
I have a express post route to '/' that returns a status with res.status(#).send() and the proper success/error block is executed based on the whether status # is 400 or 200.
Now on the update form I have the same basic setup with many more form inputs, but the AJAX code does not process the res.status(#).send() response by executing the proper success or error block, instead it is just loading a new page with the same url as the request was processed from.
The AJAX code request is similar to the top with difference of url:
submitHandler: function (form) {
$("#loader").css("display", "inline-block");
$.ajax({
type: "POST",
//The website when loaded has an invitation
//object that is passed by express
url: "/rsvp/" +invitation._id,
data: $(form).serialize(),
dataType: 'application/json'
I verified that the proper post route is running and receiving the invitation._id. It returns res.staus(#).send() but the ajax does not process the success or error block it just redirects to the requesting url but does not actually render the url.
I don't know if it is just that the form is still processing the default action, if the response from express is not correct, etc etc
I hope I have been clear on my issue and someone knows what I am doing wrong here.
Regards!
Update!
I got it working. Though the url with variable was correct and express was receiving the proper id, JS was throwing an error causing everything to crash. I never caught the error because the page would reload to the blank page and clear the console. I fixed it by saving the id in a hidden field when rendering the form and used that instead. Seems to have fixed the problem.
Thanks for looking!
Related
I'm trying to using Airtable, node.js, express.js and jquery to create a simple user authentication functionality but I'm fairly new at this and I'm running into a problem I can't seem to fix and the articles I've read I can't seem to grasp or adapt to my particular situation.
I have this Ajax call in my html doc:
$("#checkUser").submit(function(e) {
var studentID = $('input[name="student"]').val()
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data) {
$(window).attr("location", window.location.href + 'Dashboard?student=' + studentID);
},
error: function(data){
console.log("User not found. Try again");
}
});
});
This call sends the inputted username and data to the server which then processes it in the following way:
app.post('/checkUser', urlencodedParser, function(request,response){
var user = JSON.stringify(request.body);
user = JSON.parse(user);
base('RegisteredStudents').select({
filterByFormula: '{UserID} = ' + user.student,
view: "Grid view"
}).eachPage(function page(records, fetchNextPage) {
records.forEach(function(record) {
response.sendStatus(200);
});
fetchNextPage();
}, function done(error) {
response.sendStatus(404);
});
});
If the user exists in the database of Airtable, it should send '200' which the Ajax then reacts by redirecting accordingly to the user's profile. Otherwise, if the user does not exist, the server should respond with '404', which the Ajax call should react to by printing a statement in the console. While it does do these two things well, the server breaks down when, after a student puts in the wrong user ID and the Ajax prints the statement, the student tries to put once more a userID. I get the " Can't set headers after they are sent. " message. Please, how can I solve this?
Thank you!
You have two response.send..., you can only send data once. Either make sure only one runs with some conditional or add return before all response.send... so if any of them runs, the program will return and the other response.send.. will not run.
I read through a similiar post but the individual was using perl and something elss so it didn't help me. My question is how can i submit a form with node js/pug but remain on the same page.
In the pug form the method is set to POST and action set to /profile
in my nodejs i'm using
router.post("/profile", req, res, next){
return res.redirect("back")
}
The problem is that all this does is reload the page. I want to stay on the page and simple show a message saying "profile update".
Then don't return a redirect. Simply take the post data and process it, you can return the state of the operation, for example. Then however you should use an AJAX query instead of stock form, which will always redirect you to the action URL.
router.post("/profile", req, res, next){
return updateProfile(req.body); // true or false
}
And in jQuery, for example, you can perform an AJAX request
$.ajax({
type: "POST",
url: "/profile",
data: profile_form_data_object,
success: function(data) {
alert("Result of the profile update was: " + data);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am trying with passport-facebook ajax
client
$('#fb').click(function(){
$.ajax({
url:'/auth/facebook',
type: 'post',
success:function(data){
if(data.result == true){
...
}else{
...
}
},
error:function(request,status,error){
console.log("code:"+request.status+"\n"+"message:"+request.responseText+"\n"+"error:"+error);
}
})
});
error message
XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?~~~
...
Response for preflight is invalid (redirect)
i don't know this error..
help me please
Facebook does not allow scripts to load the login dialog, i guess to prevent phishing. You need to do the GET request via the browser URL by an anchor tag. Or you can get around it in your AJAX by doing:
window.location.replace('http://yourdomain/auth/facebook')
Please help me to solve this problem
i want to navigate to another frame after http module finish its request. Code below :
var datanya = 'token='+konfigurasi.tokenapps+'&email='+inputan['email']+'&nama='+inputan['nama']+'&handphone='+inputan['handphone']+'&alamat='+inputan['alamat']+'&longitude='+longi+'&latitude='+lat +'&model='+cekPlatform.device.model+'&tipe='+cekPlatform.device.deviceType+'&manufaktur='+cekPlatform.device.manufacturer
+'®ion='+cekPlatform.device.region;
httpModul.request({
url: 'http://example.com/c_user/daftar/',
method: "POST",
timeout: 10000,
headers: { "Content-Type": "application/x-www-form-urlencoded" },
content: datanya
}).then(function(response){
//console.log(JSON.stringify(response));
//console.log(response);
console.log('data diterima : '+response.content);
var jsondata = response.content.toJSON();
console.log('JSON Data hasil '+JSON.stringify(response.content));
loader.hide();
if(jsondata.hasil=='error'){
console.log('error '+jsondata.alasan);
Toast.makeText(jsondata.alasan, "long").show();
}else{
console.log('success : '+jsondata.alasan);
Toast.makeText(jsondata.alasan, "long").show();
//navigate
fm.topmost().navigate("otp/cek_daftar");
console.log('navigation passed');
}
},function(err){
//return error;
Toast.makeText('Error : '+err, "long").show();
console.log(err);
})
But it wont work with navigation. From searching i got information http module use asynchronous maybe it wont work with navigation that used synchronous.
Thanks
You can navigate fine in the download promise handler; I do so in one of my projects; download the orders then navigate to the orders screen. However, a couple things it could be:
Does fm = require ('ui/frame');
In your navigate have you tried .navigate('~/otp/cek_daftar');
Have you tried putting a Try/Catch around the navigate to see why that page isn't navigating too, you might have a bug in that page and so it is failing...
Are you getting the console: console.log('data diterima : '+response.content);
I am using post method to submit form in node js. Now when I submit the form, I want to show the error message from node server if login fails. I am setting the message as res.send("") but it is showing message on another window. So please help me to solve this?
You could make an Ajax call from your form to your node server API, then depending on the result from your server, show a message.
Jquery example:
$.ajax({
method: "POST",
url: "/api"
data: {login_data_here}
})
.success(function(msg) {
// redirect to admin area etc
})
.error(function(msg) {
// show login for with a failure message
});
Node API server would return something like this:
res.writeHead(200, { 'Content-Type': 'application/text' });
res.end('Login Success');
Or this on fail:
res.writeHead(400, { 'Content-Type': 'application/text' });
res.end('Login Fail');
You can use this module for persisted flash messages between page redirects - https://www.npmjs.com/package/connect-flash