I am trying to redirect a user to a different page after they input there correct user information and then pressing the submit button using (window.location.href) to redirect but the page keeps reloading after the form has been submitted
<form id="login" method="post">
<h1>Login students</h1>
<label for ="username">username:</label>
<input required type="username" id="username" v-model="username">
<br><br>
<label for="password">password: </label>
<input required type="password" id="password" v-model='password'>
<br><br>
<button v-on:click='onSubmit'>submit</button>
</form>
var loginApp = new Vue({
el: '#login',
data: {
username: '',
password: '',
},
methods: {
onSubmit: function () {
// check if the email already exists
var users = '';
var newUser = this.username;
var passcheck = this.password;
if (localStorage.getItem('users')) { // 'users' is an array of objects
users = JSON.parse(localStorage.getItem('users'));
}
if (users) {
if (users.some(function (user) {
return user.username === newUser & user.password === passcheck
})) {
//alert('Welcome back-' + newUser);
//window.location.href = '<index.html>' + '' + newUser;
window.location.href = "index.html";
} else {
alert('Incorrect username or password');
}
}
}
}
});
the proble is with
<form id="login" method="post">
the form doesn't have an action defined, so it makes the browsers refresh.
you need to prevent the default action either through the form element
<form v-on:submit.prevent>
or through your onsubmit handler:
methods: {
onSubmit: function (e) {
e.preventDefault()
//...
}
}
I'm converting an old LAMP stack project to use Node/Express/MongoDB instead of PHP/Laravel/MySQL. I built out my routes the same way I did in Laravel and have tested the routes I've built using Postman. Every route works as it should through testing in Postman.
However, when I try to use these routes in the display.js file that I wrote, the only route that works is GET /players. I am looking for some insight on these routes and the display file I'm using.
When I click the edit button, my GET /player/:id route grabs the correct information (status code 200 and preview shows JSON object) but will not populate the fields in my form.
When I click the delete button, I get a 404 status code with a response of "Cannot GET /players/123/delete". How do I adjust my display code to use DELETE instead of GET? (I believe I can refactor my all of my routes to just /players/:id using the correct http request method if I can figure out how to pass the request method in the display.js code).
When I try to submit a new record, I get a 400 status code with validation error saying Path age is required. It's actually the same error for each field name, so I assume that I'm not passing the values from the field into the JSON object correctly.
I haven't been able to test patch, but believe it should be remedied through fixing DELETE /players/:id and GET /players/:id.
Any help is appreciated. Code is below for display and server js files.
display.js
// this is the base url to which all your requests will be made
var baseURL = window.location.origin;
$(document).ready(function(){
// $.ajaxSetup({
// headers: {
// 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
// }
// });
$('#table').click(function(event) { // generates the table
// change the url parameters based on your API here
// Using an JQuery AJAX GET request to get data form the server
$.getJSON(baseURL+'/players', function(data) {
generateTable(data, $('#container'));
});
});
$('#form').click(function(event) {
// creating an empty form
generateForm(null, $('#container'));
});
// Handle table click event for delete
$('#container').on('click', '.delete', function(event) {
var id = $(this).val();
// change the url parameters based on your API here
// remember to create delete functionality on the server side (Model and Controller)
// Using an JQuery AJAX GET request to get data form the server
$.getJSON(baseURL+"/players/"+id+"/delete", function(data) {
//Generate table again after delete
//change the url based on your API parameters here
// Using an JQuery AJAX GET request to get data from the server
$.getJSON(baseURL+'/players', function(data) {
generateTable(data, $('#container'));
});
});
});
// Handle form submit event for both update & create
// if the ID_FIELD is present the server would update the database otherwise the server would create a record in the database
$('#container').on('submit', '#my-form', function(event) {
var id = $('#id').val();
console.log(id);
if (id != "") {
event.preventDefault();
submitForm(baseURL+"/players/"+id+"/edit", $(this));
} else {
event.preventDefault();
submitForm(baseURL+"/player", $(this));
}
});
// Handle table click event for edit
// generates form with prefilled values
$('#container').on('click', '.edit', function(event) {
// getting id to make the AJAX request
var id = $(this).val();
// change the url parameters based on your API here
// Using an JQuery AJAX GET request to get data form the server
$.getJSON(baseURL+'/players/'+id, function(data) {
generateForm(data, $('#container'));
});
});
// function to generate table
function generateTable(data, target) {
clearContainer(target);
//Change the table according to your data
var tableHtml = '<table><thead><tr><th>Name</th><th>Age</th><th>Position</th><th>Team</th><th>Delete</th><th>Edit</th></tr></thead>';
$.each(data, function(index, val) {
tableHtml += '<tr><td>'+val.playername+'</td><td>'+val.age+'</td><td>'+val.position+'</td><td>'+val.team+'</td><td><button class="delete" value="'+val._id+'">Delete</button></td><td><button class="edit" value="'+val._id+'">Edit</button></td></tr>';
});
tableHtml += '</table>';
$(target).append(tableHtml);
}
// function to generate form
function generateForm(data, target){
clearContainer(target);
//Change form according to your fields
$(target).append('<form id="my-form"></form>');
var innerForm = '<fieldset><legend>Player Form</legend><p><label>Player Name: </label>'+'<input type="hidden" name="id" id="id"/>'+'<input type="text" name="playername" id="playername" /></p>' + '<p><label>Age: </label><input type="text" name="age" id="age" /></p>'+ '<p><label>Hometown: </label><input type="text" name="city" id="city" />'+ ' ' + '<input type="text" name="country" id="country" /></p>' + '<p><label>Gender: </label><input type="text" name="gender" id="gender" /></p>'+ '<p><label>Handedness: </label><input type="text" name="handedness" id="handedness" /></p>'+ '<p><label>Broom: </label><input type="text" name="broom" id="broom" /></p>'+ '<p><label>Position: </label><input type="text" name="position" id="position" /></p>'+ '<p><label>Team: </label><input type="text" name="team" id="team" /></p>'+ '<p><label>Favorite Color: </label><input type="text" name="favoritecolor" id="favoritecolor" /></p>'+ '<p><label>Headshot: </label><input type="text" name="headshot" id="Headshot" /></p>'+ '<input type="submit"/>';
$('#my-form').append(innerForm);
//Change values according to your data
if(data != null){
$.each(data, function(index, val) {
$('#id').val(val._id);
$('#playername').val(val.playername);
$('#age').val(val.age);
$('#city').val(val.city);
$('#country').val(val.country);
$('#gender').val(val.gender);
$('#handedness').val(val.handedness);
$('#broom').val(val.broom);
$('#position').val(val.position);
$('#team').val(val.team);
$('#favoritecolor').val(val.favoritecolor);
$('#Headshot').val(val.headshot);
});
}
}
function submitForm(url, form){
$.post(url, form.serialize(), function(data) {
showNotification(data, $('#notification'));
});
}
function showNotification(data, target){
clearContainer(target);
target.append('<p>'+data+'</p>');
}
function clearContainer(container){
container.html('');
}
});
server.js
const _ = require('lodash');
const {ObjectID} = require('mongodb');
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
var {mongoose} = require('./db/mongoose');
var {Player} = require('./models/player');
var app = express();
const port = process.env.PORT || 3000;
app.use(express.static(__dirname+'./../public'));
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.sendFile('index.html');
});
app.post('/player', (req, res) => {
var player = new Player({
playername: req.body.playername,
age: req.body.age,
city: req.body.city,
country: req.body.country,
gender: req.body.gender,
handedness: req.body.handedness,
broom: req.body.broom,
position: req.body.position,
team: req.body.team,
favoritecolor: req.body.favoritecolor,
headshot: req.body.headshot
});
player.save().then((doc) => {
res.send(doc);
}, (e) => {
res.status(400).send(e);
});
});
app.get('/players', (req, res) => {
Player.find().then((players) => {
res.send(players);
}, (e) => {
res.status(400).send(e);
});
});
app.get('/players/:id', (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Player.findById(id).then((player) => {
if (player) {
res.send(player);
} else {
return res.status(404).send();
}
}).catch((e) => {
res.status(400).send();
});
});
app.delete('/players/:id/delete', (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Player.findByIdAndRemove(id).then((player) => {
if (player) {
res.send(player);
} else {
return res.status(404).send();
}
}).catch((e) => {
res.status(400).send();
});
});
app.patch('/players/:id/edit', (req, res) => {
var id = req.params.id;
var body = _.pick(req.body, ['playername', 'age', 'city', 'country', 'gender', 'handedness', 'broom', 'position', 'team', 'favoritecolor', 'headshot']);
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Player.findByIdAndUpdate(id, {$set: body}, {new: true}).then((player) => {
if (!player) {
return res.status(404).send();
} else {
res.send(player);
}
}).catch((e) => {
res.status(400).send();
})
});
app.listen(port, () => {
console.log(`Started on port ${port}`);
});
module.exports = {app};
When I click the delete button, I get a 404 status code with a response of "Cannot GET /players/123/delete". How do I adjust my display code to use DELETE instead of GET? (I believe I can refactor my all of my routes to just /players/:id using the correct http request method if I can figure out how to pass the request method in the display.js code).
This is because your app has app.delete('/players/:id/delete') and not app.get('/players/:id/delete'). However, your server side code shouldn't change much, just one tweak:
If you have an app.delete() then really no need to have the verb delete at the end of the resource.
Also you need to make the request using the HTTP Method DELETE instead of making a GET in display.js. Just make the DELETE request using $.ajax() with type set to 'DELETE'
When I click the edit button, my GET /player/:id route grabs the correct information (status code 200 and preview shows JSON object) but will not populate the fields in my form.
This is because your implementation of $.each() assumes data will always be an Array and not ever and object, however, your generateForm() is passing in a Player object. Change your $.each() to do type checking for array handling and object handling. See below changes.
When I try to submit a new record, I get a 400 status code with validation error saying Path age is required. It's actually the same error for each field name, so I assume that I'm not passing the values from the field into the JSON object correctly.
If you make the above change to generateForm() it should fix this.
Just take the below snippets and replace those sections within your app, it should work.
server.js
app.delete('/players/:id', (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
return Player.findByIdAndRemove(id).then((player) => {
if (player) {
res.status(200).json(player);
} else {
return res.status(404).send();
}
}).catch((e) => {
res.status(400).send();
});
});
app.patch('/players/:id', (req, res) => {
var id = req.params.id;
var body = _.pick(req.body, ['playername', 'age', 'city', 'country', 'gender', 'handedness', 'broom', 'position', 'team', 'favoritecolor', 'headshot']);
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Player.findByIdAndUpdate(id, {$set: body}, {new: true}).then((player) => {
if (!player) {
return res.status(404).send();
} else {
res.status(200).json(player);
}
}).catch((e) => {
res.status(400).send();
})
});
app.post('/players', (req, res) => {
var player = new Player({
playername: req.body.playername,
age: req.body.age,
city: req.body.city,
country: req.body.country,
gender: req.body.gender,
handedness: req.body.handedness,
broom: req.body.broom,
position: req.body.position,
team: req.body.team,
favoritecolor: req.body.favoritecolor,
headshot: req.body.headshot
});
return player.save().then((doc) => {
return res.status(200).json(doc);
}, (e) => {a
return res.status(400).send(e);
});
});
display.js
// Handle form submit event for both update & create
// if the ID_FIELD is present the server would update the database otherwise the server would create a record in the database
$('#container').on('submit', '#my-form', function(event) {
var id = $('#id').val();
let formData = {};
$.each($('#myForm').serializeArray(), function(_, kv) {
if (formData.hasOwnProperty(kv.name)) {
formData[kv.name] = $.makeArray(formData[kv.name]);
formData[kv.name].push(kv.value);
}
else {
formData[kv.name] = kv.value;
}
});
console.log(id);
if (id != "") {
event.preventDefault();
$.ajax({
url: baseURL + '/players/' + id,
type: 'PATCH',
success: function(edited) {
// Handle returned edited player
}
})
} else {
event.preventDefault();
$.ajax({
url: baseURL + '/players',
type: 'POST',
success: function(created) {
// Handle created player
}
})
}
});
// Handle table click event for delete
$('#container').on('click', '.delete', function(event) {
var id = $(this).val();
// change the url parameters based on your API here
// remember to create delete functionality on the server side (Model and Controller)
// Using an JQuery AJAX GET request to get data form the server
$.ajax({
url: baseURL + '/players/' + id,
type: 'DELETE',
success: function(data) {
//Generate table again after delete
//change the url based on your API parameters here
// Using an JQuery AJAX GET request to get data from the server
$.getJSON(baseURL+'/players', function(data) {
generateTable(data, $('#container'));
});
}
});
});
// function to generate form
function generateForm(data, target){
clearContainer(target);
//Change form according to your fields
$(target).append('<form id="my-form"></form>');
var innerForm = '<fieldset><legend>Player Form</legend><p><label>Player Name: </label>'+'<input type="hidden" name="id" id="id"/>'+'<input type="text" name="playername" id="playername" /></p>' + '<p><label>Age: </label><input type="text" name="age" id="age" /></p>'+ '<p><label>Hometown: </label><input type="text" name="city" id="city" />'+ ' ' + '<input type="text" name="country" id="country" /></p>' + '<p><label>Gender: </label><input type="text" name="gender" id="gender" /></p>'+ '<p><label>Handedness: </label><input type="text" name="handedness" id="handedness" /></p>'+ '<p><label>Broom: </label><input type="text" name="broom" id="broom" /></p>'+ '<p><label>Position: </label><input type="text" name="position" id="position" /></p>'+ '<p><label>Team: </label><input type="text" name="team" id="team" /></p>'+ '<p><label>Favorite Color: </label><input type="text" name="favoritecolor" id="favoritecolor" /></p>'+ '<p><label>Headshot: </label><input type="text" name="headshot" id="Headshot" /></p>'+ '<input type="submit"/>';
$('#my-form').append(innerForm);
//Change values according to your data
if(data instanceof Array){
$.each(data, function(index, val) {
$('#id').val(val._id);
$('#playername').val(val.playername);
$('#age').val(val.age);
$('#city').val(val.city);
$('#country').val(val.country);
$('#gender').val(val.gender);
$('#handedness').val(val.handedness);
$('#broom').val(val.broom);
$('#position').val(val.position);
$('#team').val(val.team);
$('#favoritecolor').val(val.favoritecolor);
$('#Headshot').val(val.headshot);
});
}
else if (typeof data === 'object') {
$.each(data, function(key, value) => {
$('#' + key).val(value);
});
}
}
Try res.json(player); instead of res.send(player); in order to send the data in JSON format.
Also, instead of $.post(url, form.serialize(), function(data) {try the code from this answer in order to send the data in JSON format.
First of all I am new to React so if there's something to improve tell me.
I have a login form that sends the information with ajax to php,I want to catch the error and update a p element althought i cannot find the way to do it.
When it's wrong the message that I send with php i want to call another method however it says undefined.
var APP = React.createClass({
getInitialState:function(){
return{user:'',pass:'',message:''};
},
setUser:function(e){
this.setState({user:e.target.value});
},
setPass:function(e){
this.setState({pass:e.target.value});
},
setErrors:function(errors){
alert('calling');
this.setState({message:errors});
},
handleForm:function(e){
e.preventDefault();
var username = this.state.user;
var password = this.state.pass;
$.ajax({
'url':'prg/loginJSON.php',
'type':'POST',
data:{'username':username,'password':password},
success:function(result){
if(result.error){
window.location.href="http://localhost/learnSeries/home.html";
sessionStorage.setItem('cookiePass',result.token);
}
else{
this.setErrors(result.message);
}
},
error:function(xhr){
console.log('error ajax' +xhr.responseText);
}
});
},
render:function(){
return(
<form onSubmit={this.handleForm} id="loginForm" method="post" action="" role="form">
<label className="is-required">User</label>
<input type="text" name="username" onChange={this.setUser} id="username" required placeholder="User"></input>
<label className="is-required">Password</label>
<input type="password" name="password" onChange={this.setPass} id="password" required placeholder="Password"></input>
<input type="submit" value="Log In"></input>
<p>{this.state.message}</p>
</form>
)
}
});
React.render(<APP />, document.getElementById('site'));
The this in the success function is not the same as when you started the request with $.ajax. You have to remember it and use it instead of this later on (in my
handleForm:function(e){
// ...
// -->
var self = this;
// <--
$.ajax({
// ...
success:function(result){
if(result.error){
// ...
}
else{
// -->
self.setErrors(result.message);
// <--
}
},
// ...
});
I'm attempting to write a jQuery script to store an authentication token from a REST API service. I had a block of working code but decided to modularize to make the application more scalable. Now, it seems that the preventDefault portion is no longer working.
<form action="/" id="authorize">
<label for="username">Username:</label><br />
<input type="text" id="username" required /><br />
<label for="password">Password:</label><br />
<input type="password" id="password" required /><br />
<input type="submit" value="Authorize" /><span id="isValid" class="checkContainer"> </span>
</form><hr />
<label for="serviceType" class="fieldDisabled">Method: </label>
<select id="serviceType" disabled>
<option></option>
<option value="option1">Option 1</option>
<option value="option2">Option 2</option>
</select>
The script is saved separately as authorize.js and invoked in the module as follows:
<script src="js/authorize.js"></script>
<script>
$(document).ready(function() {
Authorize.init();
});
</script>
Here's the module itself:
var s;
var Authorize = {
token: null,
settings: {
username: $("#username"),
password: $("#password"),
form: $("#authorize"),
validationIcon: $("#isValid"),
selector: $("#serviceType"),
selectorLabel: $("label[for='serviceType']"),
serviceSelector: $(".methodFieldDisabled"),
url: "redacted"
},
init: function() {
s = Authorize.settings;
this.bindUIActions();
},
bindUIActions: function() {
s.form.submit(function(event) {
event.preventDefault();
data = Authorize.buildJSON(s.username.val(), s.password.val());
Authorize.getToken(json);
});
},
buildJSON: function(username, password) {
var data = {};
data['grant_type'] = password;
data['username'] = username;
data['password'] = password;
return data;
},
getToken: function(data) {
$.ajax({
type: "POST",
url: s.url,
data: data,
success: function(json) {
Authorize.success(json);
},
error: function(json) {
Authorize.error(json);
}
});
},
success: function(json) {
Authorize.token = json.accessToken;
Authorize.revealServiceSelector();
},
error: function(json) {
Authorize.hideServiceSelector();
},
revealServiceSelector: function() {
s.serviceSelector.hide();
if(s.validationIcon.hasClass("invalid")) {
s.validationIcon.removeClass("invalid");
}
selectorLabel.removeClass("fieldDisabled");
selector.prop("disabled", false);
s.validationIcon.addClass("valid");
},
hideServiceSelector: function() {
s.serviceSelector.hide();
if(s.validationIcon.hasClass("valid")) {
s.validationIcon.removeClass("valid");
}
selectorLabel.addClass("fieldDisabled");
selector.prop("disabled", "disabled");
s.validationIcon.addClass("invalid");
}
};
I've been toiling over this for about a day now and can't seem to locate the point of failure. When the form is submitted, it redirects to the root directory of the server instead of executing the script as intended.
Just a few typos which stopped the code in its tracks. The submission was the default behavior as your code failed to complete.
Use a debugger to see the errors at runtime (get to know and love your F12 debugging tools in Chrome etc!):
1) You have the wrong variable (json instead of data) on the line below so you get an error:
bindUIActions: function () {
s.form.submit(function (event) {
event.preventDefault();
data = Authorize.buildJSON(s.username.val(), s.password.val());
Authorize.getToken(data); // <<<<<<<<<<<<<<<<<<<<<<<
});
2) You also failed to put your scope (s) on a couple of variables:
revealServiceSelector: function () {
s.serviceSelector.hide();
if (s.validationIcon.hasClass("invalid")) {
s.validationIcon.removeClass("invalid");
}
s.selectorLabel.removeClass("fieldDisabled");
s.selector.prop("disabled", false);
s.validationIcon.addClass("valid");
},
hideServiceSelector: function () {
s.serviceSelector.hide();
if (s.validationIcon.hasClass("valid")) {
s.validationIcon.removeClass("valid");
}
s.selectorLabel.addClass("fieldDisabled");
s.selector.prop("disabled", "disabled");
s.validationIcon.addClass("invalid");
}
Your from action is pointed to "\" which is the root of your directory. Instead point it to the file that contains the code you want to fire.
I have a form which I am submitting to my database, the form includes Jquery Validate plugin and ajax to submit.
The issue I am having is that after I click submit the form does not clear, it updates to database etc but I am just trying to clear the form and css highlight on the input field so someone could add a new record. Any help please?
CODE:
$(document).ready(function () {
$.validator.addMethod("time", function (value, element) {
return this.optional(element) || /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(value);
}, "Please enter a valid time.");
$("#newform").validate({
//validation
debug: false,
rules: {
Name: {
required: true,
minlength: 3,
},
Surname: {
required: true,
},
},
submitHandler: function (form) {
$.post('process.php', $("#newform").serialize(), function (data) {
$('#results').html(data);
$('#newform').reset();
});
}
});
});
HTML:
<form name="newform" id="newform" action="" method="POST">
<p>Name:</p>
<input type="text" id="pName" name="sName" /><br />
<p>Surname:</p>
<input type="date" id="pSName" name="pSName" /><br />
<input type="submit" name="submit" value="Submit">
</form>
<div id="results"><div>
You can use the following code to clear your form:
$('#newform').reset();
To focus on a specific <input> then you can use this after the reset() call:
$('input[name="sName"]').focus();
Try the following:
submitHandler: function (form) {
var jqxhr = $.post('process.php', $("#newform").serialize(), function (data) {
$('#results').html(data);
});
jqxhr.done(function() {
$('#newform')[0].reset();
});
}
$('#newform').reset();
The above code will do. But reading your comments I see that you will have to make the ajax call synchronous. Because if its asynchronous, you will clear the form before the submit request is actually processed on server side. That's the reason you see a clear form before process.php
In the ajax call pass async also in the object parameter-
{url:'xyz.com',async:false}