This is the strangest problem i ever had, this is the view (in jade):
extends layout
block content
h1 Edit chatroom!!
form(method="POST")
fieldset.form-group
label(for="name") Name:
input.form-control(name="name", type="text", placeholder="Enter a name" value="#{room.name}")
small.text-muted Give your chatroom a meaningful name for people to refer to it.
button.btn.btn-primary(type="submit") Save chatroom
a.btn.btn-default(href="/admin/rooms") Cancel
this is the form source from the page source code returned to the browser :
<form method="POST">
<fieldset class="form-group"><label for="name">Name:</label><input name="name" type="text" placeholder="Enter a name" value="independents" class="form-control"><small class="text-muted">Give your chatroom a meaningful name for people to refer to it.</small></fieldset>
<button type="submit" class="btn btn-primary">Save chatroom</button>Cancel
</form>
when i press the "Save chatroom" button i get this error message on the web page :
Cannot GET /admin/rooms/edit/
this express router is supposed to handel the form submission
router.route('/rooms/edit/:id')
.all(function(req, res, next) {
var roomid = req.params.id;
var room = _.find(rooms, r => r.id == roomid);
if (!room) {
res.sendStatus(404);
return;
}
res.locals.room = room;
next();
}).get(function(req, res) {
res.render('edit');
}).post(function(req, res) {
res.locals.room.name = req.body.name;
//res.redirect(req.baseUrl + '/rooms'); or we can also
res.redirect('./'); // but this is not good because if we had http://localhost:3000/admin/rooms/add/ it will take us to /add
});
the whole code for this small express app(two js files) exist in this previous question i wrote.
In your route defintion you have
if (!room) {
res.sendStatus(404);
return;
}
And it looks like in your code, you're not submitting any request to a URL that has an ID, so it's returning 404 just like you told it to.
Unless you're on a URL that does have an ID. What does the URL look like on the page this is on?
Related
I'm trying to set up a really simple page to render documents based on inputs. I have a form with some inputs on one page, and I want the data appear on the next page when submitted.
I'm still learning Next and I'm trying to use the pages/api to do this but I am not sure how exactly it works.
As of now when I submit the form it is redirecting me to a JSON page with the data, how can I make is so when I hit submit, it uses the JSON data to redirect to another page displaying it?
Here is the code:
index.js
export default function Home() {
return (
<>
<h1 Name Generator</h1>
<form action="/api/form" method="post">
<div>
<label for="name">Name</label>{" "}
<input
type="text"
id="name"
name="name"
placeholder="Enter name."
required
/>
</div>
<div>
<button style={{ display: "flex" }} type="submit">
Submit
</button>
</div>
</form>
</>
);
}
pages/api/form.js
export default function handler(req, res) {
// Get data submitted in request's body.
const body = req.body;
// Optional logging to see the responses
// in the command line where next.js app is running.
console.log("body: ", body);
// Guard clause checks for name,
// and returns early if they are not found
if (!body.subject || !body.teachers) {
// Sends a HTTP bad request error code
return res.status(400).json({ data: "name not found" });
}
// Found the name.
// Sends a HTTP success code
res.status(200).json({
data: {
name: `${body.name}`,
},
});
}
here is the result page I want it to render the data into and what I tried
result.js
import { data } from "../pages/api/form";
export default function Result() {
console.log(data);
return (
<>
<>
<h1>Name Generator</h1>
<hr></hr>
<div>
<h4>Name</h4>
<hr></hr>
{data.name}
</div>
</>
))
</>
);
}
When I submit I get JSON at
host/api/form
data: {
name: "name"
}
I am not sure what to try as I believe there is a simple way to do this that I am just missing
I am trying use a check box to send all selected users to a new page and am wondering how this could be done (using mongodb to store information) My existing code is as follows,
first I render the page
router.get("/admin", ensureAuthenticated,(req, res) => {
User.find()
.then(user => {
res.render("admin", {
user: user,
});
})
});
For all of the users the website has I create a check box, and all selected users should get sent to a new page
<% for (i in user) { %>
<form action="/admin" method="POST">
<label for="checkbox"><%=user[i].name%></label>
<input type="checkbox" id="user" name="user">
</form>
<% } %>
<button type="submit">View Profile</button>
however when I console log it says that user info is undefined.
router.post("/admin", (req, res) => {
profile = req.body.name
console.log(`user info: ${profile}`)
res.redirect("/admin/userprofile")
router.get("/admin/userProfile", ensureAuthenticated,(req, res) => {
res.render("admin_user_profile", {
user: profile
})
});
})
any help will be greatly appreciated, thanks
Your page contains one <form> element per user but only one submit button overall. Either include the submit button in the <form>, but then you can only submit one of the users. Or move the <form> and </form> outside the for loop (and </form> after the submit button) and give every <input> a unique name, for example,
<input type="checkbox" id="<%=user[i].name%>" name="<%=user[i].name%>">
Then you can submit all checkboxes at once.
Next, your server-side code refers to req.body.name, where should that come from? req.body should contain one entry per user name, with the names of your <input> elements. And req.body.firstusername === "on" if the corresponding checkbox was selected.
In other words, you should get an object like
req.body = {
"firstusername": "on",
"thirdusername": "on"
}
if the first and third usernames are selected and the second is not selected.
I'm working on a project that I need from login, to compare the information at the form with the database. And later, after doing the validation, I need to load the information of a login in another page (I have no idea how).
(I tried to find some tutorials, but all of them use Express, that I'm not allowed to)
Now my code:
HTML (I think this part is OK, cause I could save the information in $scope.u)
<form ng-controller = "login" ng-submit="submit(user)">
<label>Login:</label>
<input type="text" ng-model="user.login" required>
<label>Senha:</label>
<input type="password" ng-model="user.pwd" required>
<label><input type="checkbox"> Lembre-me</label>
<button type="submit" class="btn btn-default">Login</button>
<p>{{user.login}}</p>
<p>{{user.pwd}}</p>
<p>LOGIN:{{user.login}}</p>
<p>SENHA:{{user.pwd}}</p>
</form>
Angular (I'm not sure if I understood the idea of $http.post, so I don't know if I can send the info of $scope.u to Nodejs)
app.controller('login',function($scope,$http){
$scope.u = {};
$scope.submit = function(user) {
$scope.u = angular.copy(user);
console.log($scope.u);
};
$http.post('/servico/login', $scope.u).success(function(data, status) {
console.log('Data posted successfully');
});
});
Node (If I could use the information of $scope.u, my problem would be finished there, but I don't know how I can load the information in another page)
The button Login should compare the values from the form and them, maybe, use to send to the other page.
function login(request,response){
var queryString = 'SELECT uLogin,uSenha FROM usuarios';
connection.query(queryString,function(err,rows){
});
}
I hope I've been clear with my doubt.
Thanks for your help.
Alright let's put it this way: How can I "redirect" a user to another page, "MyPage.php" after submitting a form that looks like this:
<form action="http://www.example.com/APageICanNotEdit.php" method="POST">
<input type="submit" name="send" value="Go" />
</form>
Please note that, I don't have control over the URL provided in the action attribute. It's an external source. Which means, I cannot edit the "APageICanNotEdit.php" file.
Here is what I want:
User will click on submit button (Labeled as Go)
action="http://www.example.com/APageICanNotEdit.php" - this action
must be performed, if possible, without displaying the contents of it.
I want the user to reach "MyPage.php" safely after
"APageICanNotEdit.php" is executed.
I need a solution without changing the URL in action, cause that
defeats the purpose.
use an hidden parameter like
<input type="hidden" name="action" value="1" />
Your form will look like this:
<form action="http://www.example.com/form-manager.php" method="POST">
</form>
Yout form manager will look like this:
if ($_POST['action'] == "1")
require_once('ThePHPFileIDoNotWantToBeLoadedOnBrowser.php");
Seeing your comment, you can do it with an AJAX call:
$(document).on('submit' , 'form[action="http://www.example.com/ThePHPFileIDoNotWantToBeLoadedOnBrowser.php"]' , function(e){
var formData = $(this).serialize(); // if you need any of the vars
$.ajax({
url:'someOtherURL.php',
type:'POST',
datatype:'json',
data: formData,
success : function(data){
for(var i = 0; i < data.length; i++){
console.log(data);
}
},
error : function(s , i , error){
console.log(error);
}
});
return true; // keep normal behavior
});
I have a form field (email signup) on the site, and the email provider wants me to submit it to their REST web service and get a response. I've never used JSON or AJAX before so floundering!
The HTML:
<form>
<input type="hidden" name="gid" value="12345678">
<input type="hidden" name="user.CustomAttribute.NewsletterPopUp" value="Global">
<input type="hidden" name="user.CustomAttribute.NewsletterOptIn" value="True">" value="True">
<input type="text" name="uemail" class="email_input_field" value="please enter your email" size="30" maxlength="64" onFocus="clearText(this)">
<input type="submit" name="signup" value="signup" class="email_submit_button">
</form>
Currently, using Javascript and using window.location to visit the URL (which creates the action instead of posting it) they want it converted to a form post action with XML response. What happens now:
$(".email_submit_button").click(function(){
var uemail = $('.email_input_field').val();
window.location = "http://example.com/automated/action.jsp?action=register&errorPage=/automated/action.jsp&gid=12345678&uemail="+uemail+"&user.CustomAttribute.NewsletterPopUp=Global&user.CustomAttribute.NewsletterOptIn=True";
return false;
}
});
I see you'r using jQuery so you can use the $.post to post to the server like this:
var url = "http://example.com/automated/action.jsp"
var data ={
"gid": form.gid,
"action": register,
"uemail": form.uemail,
"errorPage": "/automated/action.jsp",
"user.CustomAttribute.NewsletterOptIn": user.CustomAttribute.NewsletterOptIn,
"user.CustomAttribute.NewsletterPopUp": user.CustomAttribute.NewsletterPopUp
};
var success_func = function(data){
//do what you want with the returned data
};
$.post(url, data, success_func);
Documentation for $.post.
Or you can use the pure longer Ajax version it's mentioned in the documentation of the $.post.
EDIT:
I forget you can't do xhttpresuext to a different domain you need to use JSONP, here's a link to another SO post explaining everything by detail
Hope this help.
$(".email_submit_button").submit(function(e) {
// stop form from submitting
e.preventDefault();
// Grab all values
var uemail = $('.email_input_field').val();
// make a POST ajax call
$.ajax({
type: "POST",
url: "YOUR URL", // set your URL here
data: {
uemail: uemail // send along this data (can add more data separated by comma)
},
beforeSend: function ( xhr ) {
// maybe tell the user that the request is being processed
$("#status").show().html("<img src='images/preloader.gif' width='32' height='32' alt='processing...'>");
}
}).done(function( response ) {
// do something with the received data/response
//$("#status").html(response);
});
});
Not sure if ".email_submit_button" is the class given to the submit button or the form.. you need to use the id or class given to the form and not the submit button.. hope this helps