$(document).ready(function() {
$("#loginForm").on('submit', function() {
var mail = document.getElementById("mail").value;
var password = document.getElementById("password").value;
req = $.ajax({
url: '/api/login',
type: 'POST',
data: {
email: email,
password: password
}
});
req.done(function(data) {
if (data.result == "failed") {
let messageHandler = document.getElementById("message-handler");
messageHandler.innerHTML = `<h3> username or password incorrect </h3>`;
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST">
<input type="mail" id="mail" name="mail">
<input type="text" id="password" name="password">
<input type="submit" id="loginForm">
</form>
<div id="message-handler">
</div>
When I click the button, it simply says Method not allowed because I am sending a post request from form. The js never detects the on submit event.
Thanks
What happens here in /api/login? Try to point a file like form.php or something else.
req = $.ajax({
**url: '/api/login',**
type: 'POST',
data: {
email: email,
password: password
}
});
Maybe this is the path you need to follow for your answer ;)
Use action='url' Or action='#' this will help to detect your request in browser.
Related
I almost always work with python so all this is new-ish to me. Here I am in the early stage of building a web app with a simple login page. I am trying to make it so that when I click the login button, the onclick action in the html should call the login_user function to make a rest request to the backend api I already built.
Heres the html and js function:
<div>
<label for="username">username:</label>
<input type="text" id="username" name="username">
</div>
<div>
<label for="password">password:</label>
<input type="password" id="password" name="password">
</div>
<button id="loginButton" onclick="login_user()">login</button>
<script type="text/javascript">
function login_user(path, username, password) {
'http://127.0.0.1:5000/' = path;
document.getElementById('username') = username;
document.getElementById('password') = password;
let data = {username: username, password: password};
return fetch(path, {method: "GET", body:
JSON.stringify(data)});
};
</script>
However, this won't make a request. I dont think the issue is within the javascript? I've tried to make a more simpler function that would simply redirect me to the homepage at the onclick but that wouldnt work either. I am not too sure what is going on and if you could point me in the right direction that would be amazing!
function login_user(path, username, password) {
'http://127.0.0.1:5000/' = path; // Assigning values is wrong.
...
}
You have to rewrite the function as:
function login_user() {
let path = 'http://127.0.0.1:5000/';
let username = document.getElementById('username');
let password = document.getElementById('password');
let data = {username: username, password: password};
return fetch(path, {method: "GET", body:
JSON.stringify(data)});
};
Is syntax error !
'http://127.0.0.1:5000/' = path;
Login function, for security, you should use POST method.
See more about fetch api: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
Try this, it seems you are getting undefined for the input values
function login_user(path, username, password) {
path = 'http://127.0.0.1:5000/';
username = document.getElementById('username').value;
password = document.getElementById('password').value;
let data = {username: username, password: password};
return fetch(path, {
method: "GET",
body: JSON.stringify(data)
});
};
<body>
<div>
<label for="username">username:</label>
<input type="text" id="username" name="username">
</div>
<div>
<label for="password">password:</label>
<input type="password" id="password" name="password" minlength="8" required>
</div>
<button id="loginButton" onclick="login_user()">login</button>
<script type="text/javascript">
function login_user() {
let path = "http://127.0.0.1:5000/api/resource";
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let data = {username: username, password: password};
fetch(path, {
headers: {
"Content-Type": "application/json"},
method: "POST",
body: JSON.stringify(data)}
);
fetch("http://127.0.0.1:5000/");
};
</script>
First, I read somewhere that we should not use XMLHttpRequest.
Second, I am a newbie in Javascript.
Third, I created a webpage to submit email and password.
<form method="POST" onsubmit="return check();">{% csrf_token %}
<p><b>Login</b></p>
<input type="email" name="email" placeholder="Email" required></input>
<input type="password" name="password" placeholder="Password" id='new_password' ></input>
<span id='message'>{{msg}}</span>
<button type="submit" onclick="check()" name="Submit"><b>Submit</b></button>
</form>
My check function is
function check() {
document.getElementById('message').innerHTML = "checking";
const url = "https://<hostname/login";
const data = {
'email' : document.getElementById('email').value,
'password' : document.getElementById('password').value
};
const other_params = {
headers : { "content-type" : "application/json; charset=UTF-8" },
body : data,
method : "POST",
mode : "cors"
};
fetch(url, other_params)
.then(function(response) {
if (response.ok) {
return response.json();
} else {
throw new Error("Could not reach the API: " + response.statusText);
}
}).then(function(data) {
document.getElementById("message").innerHTML = data.encoded;
}).catch(function(error) {
document.getElementById("message").innerHTML = error.message;
});
return true;
}
This code is not working and just redirects me to the same page again and again.
Please help me understand what am I doing wrong.
The problem with your code is that you are not "intercepting" the submit event of your form so it will execute the default behavior which is POST to itself (since it doesn't have an instruction that tells it where to go). Unless you can have a chance to stop this default behavior, the form will perform this action.
To intercept the form's submit event you have to tell the browser to watch out of this event and execute a custom function instead of using an event listener like below:
<script>
document.getElementById('whatever-form-id')
.addEventListener('submit', check);
function check(e) {
e.preventDefault();
// and now anything else you want to do.
}
</script>
This will prevent your form from posting and it will execute your function instead.
There were some errors in your code as I've checked, please use it like this
<form method="POST" onsubmit="return check();">{% csrf_token %}
<p><b>Login</b></p>
<input type="email" id = "email" name="email" placeholder="Email" required>
<input type="password" name="password" placeholder="Password" id='new_password' >
<span id='message'>{{msg}}</span>
<button type="submit" onclick="check(event)" name="Submit"><b>Submit</b> </button>
</form>
<script>
function check(event) {
event.preventDefault();
document.getElementById('message').innerHTML = "checking";
const url = "https://hostname/login";
const data = {"email" : document.getElementById('email').value,
'password' : document.getElementById('new_password').value
};
const other_params = {
headers : { "content-type" : "application/json; charset=UTF-8"},
body : data,
method : "POST",
mode : "cors"
};
fetch(url, other_params)
.then(function(response) {
if (response.ok) {
return response.json();
} else {
throw new Error("Could not reach the API: " + response.statusText);
}
}).then(function(data) {
document.getElementById("message").innerHTML = data.encoded;
}).catch(function(error) {
document.getElementById("message").innerHTML = error.message;
});
return true;
}
</script>
Then test by changing your post URL to correct one whether working or not, for more testing use browser inspector tool to see your ajax request.
I've also put it on fiddle for your live testing http://jsfiddle.net/rajender07/xpvt214o/903616/
Thanks
1) Your validation function always returns true
2) When you use fetch..then, its promises can be executed later than return statement
So your form will be refresh again and again. You should return false, and manually submit the form with JavaScript when you get an onSuccess response.
<script>
function check(event) {
document.getElementById('message').innerHTML = "checking";
const url = "https://localhost:8080/login";
const data = {
'email' : document.getElementById('email').value,
'password' : document.getElementById('new_password').value
};
const other_params = {
headers : { "content-type" : "application/json; charset=UTF-8" },
body : data,
method : "POST",
mode : "cors"
};
fetch(url, other_params)
.then(function(response) {
if (response.ok) {
alert(response.json());
} else {
throw new Error("Could not reach the API: " + response.statusText);
}
}).then(function(data) {
document.getElementById("message").innerHTML = data.encoded;
}).catch(function(error) {
document.getElementById("message").innerHTML = error.message;
});
return false;
}
</script>
<form method="POST" onsubmit="return check();">{% csrf_token %}
<p><b>Login</b></p>
<input type="email" id = "email" name="email" placeholder="Email" required></input>
<input type="password" name="password" placeholder="Password" id='new_password' ></input>
<span id='message'>{{msg}}</span>
<button type="submit" name="Submit"><b>Submit</b></button>
</form>
Update:
Page not refreshed, error message displayed:
Firstly, I would like to understand what is your object after getting the data from REST API.
Secondly, there are mistakes in the html code as well, you don't need to add onclick on the submit button when there you already have a onsubmit on the form element.
Solution,
change
onsubmit="check(event);"
function check(e) { e.preventDefault() ... } // you can remove the return true
just going off the top of my head here but you've set the Content-Type to application/json in the headers but your body is not an JSON string
try making your body match the headers by doing
const other_params = {
headers : { "content-type" : "application/json; charset=UTF-8"},
body : JSON.stringify(data),
method : "POST",
mode : "cors"
};
EDIT
So after re-reading your question, I think what is happening is you've set your button to type of submit and what is happening is when you click on the button, your form is getting posted through the good old form post and your page gets refreshed from the postback.
If you want to handle form posts yourself using fetch, change your button type to button and the form should no longer actually post then everything else will be handled by your click event handler.
ps. while you're at it, you can remove the method and onsubmit attribute from your form tag as well
So your form should look something like this
<form>
<p><b>Login</b></p>
<input type="email" name="email" placeholder="Email" required></input>
<input type="password" name="password" placeholder="Password" id='new_password' ></input>
<span id='message'>{{msg}}</span>
<button type="button" onclick="check()" name="Submit"><b>Submit</b></button>
</form>
im trying to submit an ajax post in laravel but im having some problem regarding the form's csrf token. In my form, if the conditions i set in my ajax post url has been met the first time the form has been submitted. However if i submit the form and purposely failed the conditions i set in my ajax post url in the first try, If i submit the form again i get a token mismatch exception in my ajax error log. Do i need to refresh the csrf_token every ajax post?
Below is my code
JS
$(document).on('submit','.registration-form',function(e){
e.preventDefault();
var form = $(this);
var form_url = $(this).attr("action");
var form_values = $(this).serialize();
$.ajax({
url:form_url,
type:'POST',
data:form_values,
dataType: 'json',
async:false,
success: function(result){
console.log(result);
if(result['status']==true){
location.href = result['redirect'];
}
else{
form.find(".form-details").show().html(result['message']);
}
},
error: function(ts) {
console.log(ts.responseText)
}
});
});
HTML
<form action="{{ url('login') }}" method="POST" class="registration-form">
{{ csrf_field() }}
<input type="text" name="username" class="input" placeholder="Email">
<input type="password" name="password" class="input" placeholder="Password">
<button class="button is-redbox is-flat is-fullwidth">Login</button>
</form>
Are u sure that each time that is send in ajax?
data: {
"_token": "{{ csrf_token() }}",
}
$("#cform")[0].reset();
or in plain javascript:
document.getElementById("cform").reset();
public function regenerateToken(){
session()->regenerate();
return response()->json([
'msg'=>'success',
'token'=>csrf_token()
]);
}
$('#form').submit(funtion(event) {
event.preventDefault(event);
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: form.attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
if (response.msg === 'success') {
$('#token').val(response.token);
console.log($('#token').val());
}
}
$('input[type="text"],input[type="email"] ,textarea, select').val(''); $(this).trigger('reset');
});
So, basically I am trying to send a request from my ajax post to my node js backend. Then I am trying to get the response back from the node js and update my view. Now, this is something that happens. Instead of just updating the resulttoken in the view, I can see in the console that whole html is loaded like a page. I am really confused. Please kindly point my error. This is what I tried so far.
<!DOCTYPE html>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<form id="registerSubmit">
Phonenumber:<br>
<input type="text" name="phonenumber" id="phonenumber">
<br>
Review:<br>
<input type="text" name="review" id="review">
<br><br>
<input type="submit" value="Submit" onclick="gettoken()">
<br>
Token: <%=resulttoken%>;
</form>
<script type="text/javascript">
function gettoken() {
event.preventDefault();
var phonenumber = $("#phonenumber").val();
var review = $("#review").val();
$.ajax({
url: '/home',
data: {
"phonenumber": phonenumber,
"review": review
},
error: function (err) {
console.log("ERROR",err)
},
success: function (info) {
console.log("info",info);
},
type: 'POST',
});
}
</script>
</body>
</html>
server
app.post("/home", function (req, res) {
var s = -1;
var t = -1;
var m = -1;
var phonenumber = req.body.phonenumber;
var review = req.body.review;
console.log(phonenumber);
fd.insertreview(phonenumber,review).then(function(v) {
if(v=="1") {
console.log("Your review has been inserted successfully");
s = md.getRand();
console.log("Unique number is",s);
fd.checkifuniquenumberexists(s).then(function(u){
if(u!="1"){
console.log("Unique number doesnt exist");
fd.inserttoken(s,phonenumber).then(function (p) {
if(p=="1"){
console.log("Token has been inserted successfully");
res.render('trial',{"resulttoken":s});
}
})
}
});
}
});
});
This is what loads on the console log
info <!DOCTYPE html>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<form id="registerSubmit">
Phonenumber:<br>
<input type="text" name="phonenumber" id="phonenumber">
<br>
Review:<br>
<input type="text" name="review" id="review">
<br><br>
<input type="submit" value="Submit" onclick="gettoken()">
<br>
Token: 35055;
</form>
<script type="text/javascript">
function gettoken() {
event.preventDefault();
var phonenumber = $("#phonenumber").val();
var review = $("#review").val();
$.ajax({
url: '/home',
data: {
"phonenumber": phonenumber,
"review": review
},
error: function (err) {
console.log("ERROR",err)
},
success: function (info) {
console.log("info",info);
},
type: 'POST',
});
}
</script>
</body>
</html>
The issue is this line
res.render('trial',{"resulttoken":s});
You're returning the entire page as your response, if you just need the token you can return this as part of a JSON response e.g.
res.status(200).json({ token: s });
then at the client
$.post('/home', { phonenumber, review }, res => {
// use res.token
console.log(`Token: ${res.token}`);
})
.fail(console.error);
I'm using formspree within an angular app. Everything is working except I can't seem to change the subject of the email.
Html...
<form id="bookingForm" action="https://formspree.io/your#email.com"
method="POST">
<input type="text" name="{{client.name}}">
<input type="{{client.email}}" name="_replyto">
<input type="hidden" name="_subject" value="Request from {{client.name}}">
<!-- some other info -->
<input type="submit" value="Send">
</form>
JS...
$bookingForm = $('#bookingForm');
$bookingForm.submit(function(e) {
e.preventDefault();
$.ajax({
url: '//formspree.io/your#email.com',
method: 'POST',
data: {
client: $scope.client.name,
email: $scope.client.email,
phone: $scope.client.phone,
// some other info
},
dataType: 'json',
});
});
The _replyto seems to be working but _subject is not.
Add '_subject' to your post request and remove the name attribute from the subject input field:
$bookingForm = $('#bookingForm');
$bookingForm.submit(function(e) {
e.preventDefault();
$.ajax({
url: '//formspree.io/your#email.com',
method: 'POST',
data: {
client: $scope.client.name,
email: $scope.client.email,
phone: $scope.client.phone,
_subject: "Text here"
},
dataType: 'json',
});
});