Actually I have 2 questions about form submit using jQuery and Ajax.
Currenlty, I am validating a login form using jQuery/Ajax request. I want to disabled the login submit button after logged in successfully completed. So that I am using following .js code but it's not disabled the submit button.
Questions
a) what is the issue in my js code ? why it's not disable the login submit button after logged in successfully ?
b) Using jQuery/Ajax for login is safe for security ? If not what I need to to and Should I add server side validation too ?
Thanks a lot :)
.js code for login :
// Login form
function login_form (element,event){
e= $(element);
event.preventDefault();
var formData = new FormData(e.parents('form')[0]);
$.ajax({
url: 'login_process',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function () {
$('#login_bottom').val('Validating...');
$("#login_bottom").attr("disabled", true);
},
success: function (data) {
$('.validation_msg').html(data);
$('#login_bottom').val('LOGIN');
$("#login_bottom").attr("disabled", false);
if(data == '<div class="alert alert-success"><strong>Successfully logged!.</strong></div>') {
$('#login_form')[0].reset();
$("#login_bottom").attr("disabled", true);
}
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
Login Process php page :
It's return following message after successfully logged :
if(login($email, $user_pwd) == true) {
echo '<div class="alert alert-success">';
echo '<strong>Successfully logged!.</strong>';
echo '</div>';
}
Html form :
<div class="container bellow-nav">
<div class="row">
<div class="col-md-6 content-area">
<h3>Login</h3>
<hr/>
<form role="form" method="post" id="login_form">
<div class="form-group">
<label for="email">Email addresse</label>
<input type="email" name="email" class="form-control" placeholder="Email address">
</div>
<div class="form-group">
<label for="pwd">Password</label>
<input type="password" name="pwd" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<input type="hidden" name="_token" value="<?php echo $form_token; ?>">
<input type="submit" name="submit" value="LOGIN" class="btn btn-booking" id="login_bottom" onclick="login_form(this,event);" >
</div>
<div class="form-group validation_msg">
</div>
<div class="fomr-group">
<label for=""><p>Forgot password?</p></label> |
<label for=""><p>Don't have an account? <a href="signup">Join now</p></label>
</div>
</form>
</div>
</div><!--main row-->
</div><!--main container end-->
One reason could be that the data may have some leading or trailing spaces.
You can extract only the text message from the data and use that for comparison
if ($(data).text().trim() == 'Successfully logged!.') {
$('#login_form')[0].reset();
$("#login_bottom").prop("disabled", true);
} else {
$("#login_bottom").prop("disabled", false);
}
For the second part, I assume the server side login is using a secured cookie to store the authentication information is so yes it is secured.
Use json response insted of HTML
Login Process php page : It's return following message after successfully logged :
if(login($email, $user_pwd) == true) {
echo json_encode(['message'=>'Success'])
}
$.ajax({
url: 'login_process',
type: 'POST',
dataType: 'JSON',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function () {
$('#login_bottom').val('Validating...');
$("#login_bottom").attr("disabled", true);
},
success: function (data) {
$('.validation_msg').html(data);
$('#login_bottom').val('LOGIN');
$("#login_bottom").attr("disabled", false);
if(data.message == 'Success') {
$('#login_form')[0].reset();
$("#login_bottom").attr("disabled", true);
}
},
data: formData,
cache: false,
contentType: false,
processData: false
});
First and for most, YOU MUST ADD SERVER SIDE VALIDATIONS. JavaScript can be disabled on the browser and your validations will be disabled when that happens. Javascript can also be edit on the browser and your validations will be useless js validations is only good for user friendly feeling and not for security.
All you have to do is set the disabled attribute to disabled value
$("#login_bottom").attr("disabled","disabled");
However I don't think you are going inside that if. you should console log something and make sure you are passing the if statement.
Related
I am facing an issue while sending the data through the PHP script, in Index.php there is a form with some field values and a JavaScript script included in the Index.php which posts an image after I submit the form in Index.php with help of ajax, but Image is not posting/sending through ajax, only form field submission works.
If I call only Ajax during the time of form submission that is working or if I submit the form value all alone working, but if I call together the image is not working.
Index.php
<form enctype="multipart/form-data" method="post" action="saveRecord.php">
<?php include ('imagecropinterface/index.html'); ?>
<div>
<input autocomplete="off" type="text" maxlength="90" placeholder="HeadLine" id="headline" name="headline" style="width:386px;">
</div>
<div class="mt-2">
<input autocomplete="off" type="text" maxlength="90" name="subtitle" placeholder="Sub Title" style="width:386px;">
</div>
<div>
<input id='jour' type='text' value="" class=''>
</div>
<div>
<textarea name="fullText" placeholder="Synopsis" style="width:386px;"></textarea>
</div>
<input class="btn btn-secondary" name="save" id="btnid" value="Save" type="submit">
</form>
index.html
const downloadAllBtn = document.getElementById("btnid");
downloadAllBtn.addEventListener("click", downloadAll);
function downloadAll() {
$.ajax({
type: "POST",
url: "/ap-beta2/saveRecord.php",
data: {
data: imagesBase64,
},
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" + data, err);
},
success: function (data) {
console.log(data);
},
});
}
saveRecord.php
if (isset($_POST['save']) && isset($_POST['data'])) {
echo ($_POST[data]);
echo ($_POST['headline']);
echo ($_POST['subtitle']);
}
How can I submit the form so that form value and ajax call POST together to the PHP page?
As suggested by #ADyson I have updated Ajax script, unfortunately, no progress!!
In the form, I put the id saveform
<form enctype="multipart/form-data" id = "saveform" method="post" action="saveRecord.php">
function downloadAll() {
$("#saveform").click(function (e) {
$.ajax({
type: "POST",
url: "https://myimpact.in/ap-beta2/saveRecord.php",
data: {
data: imagesBase64,
},
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" + data, err);
},
success: function (data) {
console.log(data);
},
});
e.preventDefault();
});
}
I have created a login system with PHP, however, i also added two factor authentication. I wanted to log in without having to refresh the page so it looks better when asking for the 2FA code
The way i have done this is by sending the username and password via ajax. my php script then checks this and then it would echo login or error
Here's my javascript code
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'inc/auth.php',
data: $(this).serialize(),
dataType: 'text',
success: function(data)
{
alert(data);
if (data === 'login') {
window.location = '/user-page.php';
}
else {
alert('Invalid Credentials');
}
},
});
});
});
This works fine, when i alert the data i get 'login' (without quotes, obviously) however it doesn't send me to user-page.php, instead, it gives me the invalid credentials alert. Despite the php page returning login, javascript is like "nope!"
What am i doing wrong?
Here's my form
<form class="form" id="login-form" name="login-form" method="post" role="form" accept-charset="UTF-8">
<div class="form-group">
<label class="sr-only" for="exampleInputEmail2">Gebruikersnaam</label>
<input type="username" class="form-control" id="gebruikersnaam" name="gebruikersnaam" placeholder="gebruikersnaam" required>
</div>
<div class="form-group">
<label class="sr-only" for="exampleInputPassword2">Wachtwoord</label>
<input type="password" class="form-control" id="wachtwoord" name="wachtwoord" placeholder="Password" required>
<div class="help-block text-right">Forget the password ?</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary btn-block">Sign in</button>
</div>
</form>
I run the javascript from this page via <script src="auth.js"></script>. I also tried putting it directly inside script tags witch failed too.
This is for testing purpose
I believe your dataType should be either html or json
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'inc/auth.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data)
{
alert(data);
if (data == 'login') {
window.location = '/user-page.php';
}
if (data == 'failed') {
alert('Invalid Credentials');
}
},
});
});
});
In absence of your server logic
Your php inc/auth.php FOR Testing purpose
//$gebruikersnaam= $_POST['gebruikersnaam'];
//$wachtwoord= $_POST['wachtwoord'];
$gebruikersnaam= 'nancy';
$wachtwoord= 'nancy123';
if($gebruikersnaam=='nancy' && $wachtwoord=='nancy123')
{
echo "login";
}
else
{
echo "failed";
}
As for CSRF attack mentioned by SO Scholar in the comment. you will need to generate something like md5 token that will be stored in a session. you will now send it with each request eg. in a hidden form input and verify that it matches the one on the server side. if match allow login otherwise trigger impersonation
Updates
$(document).ready(function() {
$('#login-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'inc/auth.php',
data: $(this).serialize(),
dataType: 'JSON',
success: function(data)
{
alert(data);
if (data.login == 'success') {
window.location = '/user-page.php';
}
if (data.login == 'failed') {
alert('Invalid Credentials');
}
},
});
});
});
PHP
<?php
error_reporting(0);
$gebruikersnaam= 'nancy';
$wachtwoord= 'nancy123';
if($gebruikersnaam=='nancy' && $wachtwoord=='nancy123')
{
$return_arr = array('login'=>'success');
}
else
{
$return_arr = array('login'=>'failed');
}
echo json_encode($return_arr);
I have the following form:
<form class="footer-newsletter-form" id="footer-newsletter" method="post" action="http://xxxxxx.us1.list-manage.com/subscribe/post-json?u=xxxxxxxxxxxxxxxxxxxxxxxxx&id=xxxxxxxxxx&c=?">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field" value="{% if customer %}{{ customer.email }}{% endif %}" placeholder="{{ 'general.newsletter_form.email_placeholder' | t }}" aria-label="{{ 'general.newsletter_form.newsletter_email' | t }}">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the following jquery bit:
<script type="text/javascript">
$(document).ready(function () {
function register($form) {
jQuery.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'jsonp',
contentType: "application/json; charset=utf-8",
error : function(err) { console.log('error') },
success : function(data) {
if (data.result != "success") {
console.log('success');
} else {
console.log('not success');
//formSuccess();
}
}
});
}
jQuery(document).on('submit', '.footer-newsletter-form', function(event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch(error){}
});
});
</script>
Which submits correctly. However, when I press the submit button what I expect to happen is that the page does not refresh and when I check the browser console I'll either see "success" or "not success". Instead what happens is I'm sent to a page that displays the following JSON message: ?({"result":"success","msg":"Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you."}).
So how do I take that success message (or error if there's an error) and have the page not only remain as is, but also capture the success message so I can display a "Success" alert? The success alert I know how to do. I just need help having the browser remain where it is and tell the difference between success and error.
P.S. I'm not sure if this is relevant but the platform is Shopify. I don't think Shopify does anything to prevent the submission from going through as it should or the response coming back so I don't think it is relevant.
The whole issue was the $(document).ready(function () {}); part. For some reason unbeknownst to me that causes the event.preventDefault(); method from running and the form submits regularly. If you remove the $(document).ready(function () {}); part it'll work as intended.
My final code for anyone looking in the future:
Form:
<form class="footer-newsletter-form" method="POST" id="footer-newsletter" action="https://xxxxxxxxxxxxx.us1.list-manage.com/subscribe/post-json?c=?">
<input type="hidden" name="u" value="xxxxxxxxxxxxxxxxxxxxxxxxxxx">
<input type="hidden" name="id" value="xxxxxxxxxx">
<input id="email" name="EMAIL" type="email" class="input-text required-entry validate-email footer__newsletter-field">
<button type="submit" title="Subscribe" class="button button1 hover-white footer__newsletter-button">SUBSCRIBE</button>
<div id="subscribe-result"></div>
</form>
And the JS:
<script>
function register($form) {
$.ajax({
type: "GET",
url: $form.attr('action'),
data: $form.serialize(),
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
error: function (err) {
console.log('error')
},
success: function (data) {
if (data.result != "success") {
console.log('Error: ' + data.msg);
} else {
console.log("Success");
$($form).find("div#subscribe-result").html("<p class='success-message'>Almost finished... We need to confirm your email address. To complete the subscription process, please click the link in the email we just sent you!</p>");
setTimeout(function() { $($form).find("div#subscribe-result").hide(); }, 7000);
}
}
});
}
$(document).on('submit', '#footer-newsletter', function (event) {
try {
var $form = jQuery(this);
event.preventDefault();
register($form);
} catch (error) {}
});
</script>
Ok, here is the scenario. I have already a form having some input fields, some radio buttons and an input type=file. There is a button for submitting the whole form using AJAX.
Everything was working fine, until i decided to change the input type=file with the more fancy DropZone.js
Now i have the following html code (a sample here):
<form enctype="multipart/form-data" id="test_form" name="test_form" class="form uniformForm">
<input class="form-control" type="text" value="" name="a-name" id="a-name" />
<label for="a-name">Field Name</label>
<div class="dropzone dropzone-previews" id="my-awesome-dropzone </div>
</form>
<button class="btn btn-primary btn-large" id="submitForm"> Submit </button>
I have the following js (jQuery), too:
$("button#submitForm").click(function(){
var fd = new FormData(document.getElementById("test_form"));
fd.append("label", "WEBUPLOAD");
$.ajax({
type: "POST",
url: "create_form.php",
data: fd,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
});
});
$("div#my-awesome-dropzone").dropzone({
url: "#",
paramName: "creative_file",
maxFilesize: 1,
autoProcessQueue: false
});
In documentation of Dropzone.js says that the dropzone div looks like <input type="file" name="file" />. The only difference is that i want to rename the input name as creative_file.
I have 2 question.
1) This doesn't work. When pressing the Submit button, i have FIREBUG opened and i check what it sends as POST. It sends everything except the files. No creative_file, no file at all.
2) If finally figured out how to make it works, is there any way to have a fallback with this implementation especially for the iOS or Android devices ?
1)
$("#salvar").on('click',function(e) {
if ($("#psl_titulo").val() == "") {
alert('Empty');
} else {
e.preventDefault();
if (myDropzone.getQueuedFiles().length > 0) {
myDropzone.processQueue();
} else {
$("#my-awesome-dropzone").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
window.location.href = url_redirect;
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Ocorreu um erro ao salvar ao enviar os dados. Erro: ' + textStatus);
}
});
e.preventDefault();
});
$("#my-awesome-dropzone").submit();
}
}
});
I have a form like this:
<form method="post" class="form_cnvc">
<p><input type="text" name="f_nm" value="" placeholder="type your first name"></p>
<p><input type="text" name="l_nm" value="" placeholder="type your last name"></p>
<div class="dropfile visible-lg">
<input type="file" id="image_file_input" name="image_file_input">
<span>Select Images(.jpg , .png, .bmp files) </span>
</div>
<p class="submit"><input type="submit" name="submit" value="post"></p>
</form>
I want that when the user will selects an image, it would be automatically submitted to my PHP page so that I can save it in the database and return an insert_id with the thumbnail of the picture.
I want to do it using jQuery but not able to do so.
PHP code is:
Easy, use a change trigger on your input Element and do an ajax-request inside:
$("#image_file_input").change(function() {
$.ajax({
url: "my-target-url.php",
type: "post",
dataType: 'json',
processData: false,
contentType: false,
data: {file: $("#image_file_input").val()},
success: function(text) {
if(text == "success") {
alert("Your image was uploaded successfully");
}
},
error: function() {
alert("An error occured, please try again.");
}
});
});
Create a url or route and enter it at url: tag (domain/file.php) and then code serversided stuff:
function processFileUpload() {
if(count($_FILES) > 0) {
foreach($_FILES as $file) {
//DO whatever you want with your file, save it in the db or stuff...
//$file["name"];
//$file["tmp_name"];
//Insert here bla blubb
echo "success";
}
}
die();
}