onsubmit not firing my JS - javascript

what am i missing here?
<script>
function validateLogIn(login)
{
console.log(login);
var username = $("#username").val();
var password = $("#password").val();
console.log(username, password, login);
$.ajax({
url: 'login.php', //checking the login in
data: {username:username,password:password},
type: "POST", //Method by which data being transmitted
dataType: 'json',
success: function(data)
{
console.log(data);
login.submit();
}
//else do an alert("please lgo in again");
});
return false;
}
</script>
</head>
<body>
<form action="crud.html" method="post" name="form-login" onsubmit="return validateLogIn(this);">
<input required placeholder="Username" type="text" name="username" id="username"/>
<input required placeholder="Password" type="password" name="password" id="password"/>
<label for="remember">Remember Me:</label>
<input type="checkbox" name="remember" value="yes">
<br />
<br />
<input type="submit" name="login" value="login" />
</form>
</body>
have i got a spelling mistake? my console.logs doesnt show either

In your validateLogIn() function, you aren't returning false, therefore the function will be called, but the browser will still proceed to submit the form to crud.html and change page.
function validateLogIn(login)
{
...
...
...
return false;
}
If you want to submit to crud.html only after the success function fires, then you still need the above return false, and in your success function add:
success: function(data)
{
login.submit();
}

This code is working perfectly on my machine, please make sure you are including the jquery library correctly. and obviously return false
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
function validateLogIn()
{
var username = $("#username").val();
var password = $("#password").val();
console.log(username, password, this);
alert("Hello");
$.ajax({
url: 'login.php', //checking the login in
data: {username:username,password:password},
type: "POST", //Method by which data being transmitted
dataType: 'json',
success: function(data)
{
console.log(data);
}
//else do an alert("please lgo in again");
});
return false;
}
</script>
</head>
<body>
<form action="crud.html" method="post" name="form-login" onsubmit="return validateLogIn();">
<input required placeholder="Username" type="text" name="username" id="username"/>
<input required placeholder="Password" type="password" name="password" id="password"/>
<label for="remember">Remember Me:</label>
<input type="checkbox" name="remember" value="yes">
<br />
<br />
<input type="submit" name="login" value="login" />
</form>
</body>
</html>

change your log statement to this as below, the log() method takes one argument, so if you want to print three variables append it to one string
console.log("username:"+username+" password:"+password+" id:"+login.id);

Related

How can I fix my Mturk submit button? It is not working

When I submitted my external HIT on Mturk, the Submit button is not working. I would appreciate if someone could help me with this. The data gets stored in my server though. Here is my code:
<div id="instruction3" class="instructions" style="display:none">
survey questions here
Submit
</div>
function SaveData() {
(some code here)
d = {
"trialStruct": trialStruct,
"critStruct": critStruct
};
console.log(d)
SendToServer(curID, d);
}
<form action="https://workersandbox.mturk.com/mturk/externalSubmit" id="mturk_form" method="post" name="mturk_form">
<input id="assignmentId" name="assignmentId" type="hidden" value="" />
<p><input id="submitButton" type="submit" value="Submit" /></p>
</form>
function SendToServer(id, curData) {
$.ajax({
type : "POST",
url : "https://xxxxxxxxxxxx/turk/save.php",
data : { json : JSON.stringify(curData) },
success : function(data) {
document.forms[0].submit();
}
});
}
Edited: the flow should be participants click on the submit button and the data gets stored and sent to the externalSubmit page. These are parts of the code from Mturk that I need to implement in my code and perhaps I am not doing it right.
<!-- HTML to handle creating the HIT form -->
<form action="https://workersandbox.mturk.com/mturk/externalSubmit" id="mturk_form" method="post" name="mturk_form">
<input id="assignmentId" name="assignmentId" type="hidden" value="" />
<!-- HTML to handle submitting the HIT -->
<p><input id="submitButton" type="submit" value="Submit" /></p>
</form>
You should call the SaveData() function inside the form tag
<form action="https://workersandbox.mturk.com/mturk/externalSubmit" id="mturk_form" method="post" name="mturk_form" onSubmit="SaveData()">
So I think you should try to move the SaveData function to the onSubmit value of the form. So you would be submitting the form and the data would get saved to the server. You have extra html code above but I think that is superfluous for what you are trying to do.
function SaveData() {
(some code here)
d = {
"trialStruct": trialStruct,
"critStruct": critStruct
};
console.log(d)
SendToServer(curID, d);
}
function SendToServer(id, curData) {
$.ajax({
type : "POST",
url : "https://xxxxxxxxxxxx/turk/save.php",
data : { json : JSON.stringify(curData) },
success : function(data) {
document.forms[0].submit();
}
});
}
<form action="https://workersandbox.mturk.com/mturk/externalSubmit" id="mturk_form" method="post" name="mturk_form" onSubmit="SaveData()">
<input id="assignmentId" name="assignmentId" type="hidden" value="" />
<p><input onclick="window.location.href = https://workersandbox.mturk.com/mturk/externalSubmit';"id="submitButton" type="submit" value="Submit" /></p>
</form>
Here is the working one, I have used https://postman-echo.com/post just to make sure it works.
function SaveData() {
var d = {
"trialStruct": trialStruct,
"critStruct": critStruct
};
console.log(d);
SendToServer(curID, d);
}
function SendToServer(id, curData) {
$.ajax({
type: "POST",
url: "https://postman-echo.com/post",
data: {
json: JSON.stringify(curData)
},
success: function(data) {
$("#mturk_form").submit();
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="instruction3" class="instructions" style="display:none">
Submit
</div>
<form action="https://postman-echo.com/post" id="mturk_form" method="post" name="mturk_form">
<input id="assignmentId" name="assignmentId" type="hidden" value="" />
<p><input id="submitButton" type="submit" value="Submit" /></p>
</form>

Invisible reCaptcha AJAX Call

I'm trying to implement the invisible reCaptcha onto a website. But I can not get it working. Here is what I'm doing:
header
<!-- Invisible reCaptcha -->
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
form.php
<form id="contact-form" class="contact-form" action="#contact">
<p class="contact-name">
<input id="contact_name" type="text" placeholder="Full Name" value="" name="name" />
</p>
<p class="contact-email">
<input id="contact_email" type="text" placeholder="Your E-Mail Address" value="" name="email" />
</p>
<p class="contact-message">
<textarea id="contact_message" placeholder="Your Message" name="message" rows="15" cols="40"></textarea>
</p>
<p class="contact-submit">
<a type="submit" id="contact-submit" class="submit" href="#">Send Your Email</a>
</p>
<div id="recaptcha" class="g-recaptcha" data-sitekey="6LceN0sUAAAAAPvMoZ1v-94ePuXt8nZH7TxWrI0E" data-size="invisible" data-callback="onSubmit"></div>
<div id="response">
</div>
</form>
script.js
// contact form handling
$(function() {
$("#contact-submit").on('click',function() {
$contact_form = $('#contact-form');
var fields = $contact_form.serialize();
var test = grecaptcha.execute();
console.log(fields);
console.log(test);
$.ajax({
type: "POST",
url: "assets/php/contact.php",
data: fields,
dataType: 'json',
success: function(response) {
if(response.status){
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$('#response').empty().html(response.html);
}
});
return false;
});
});
contact.php
private function validateFields(){
// Check reCaptcha
if(!$this->captcha){
echo "Please fill out the reCaptcha correctly";
}
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretkey."&response=".$this->captcha."&remoteip=".$_SERVER['REMOTE_ADDR']);
if(intval($responseKeys["success"]) !== 1) {
echo "You are a bot! GO AWAY!";
}
The backend (contact.php) is working fine, if g-recaptcha-response is not null. However my Problem is that g-recaptcha-response (in var fields and test) is always empty when I try to do it. When I show the recaptcha on the form and fill it out, the g-recapcha-response is not empty and everything works fine.
I know that I must invoke the grecaptcha.execute() somewhere, but even if I do, the variable is empty. How do programmaticaly call the this?
I appreciate every help! Thank you in advance!
You are missing the onSubmit() callback function.
To rearrange your js to utilize the function, this would be your new js block:
<script>
// this block must be defined before api.js is included
function onSubmit(token) {
var fields = $('#contact-form').serializeArray(); // get your form data
fields.push({name: "g-recaptcha-response", value: token});// add token to post
$.ajax({
type: "POST",
url: "assets/php/contact.php",
data: fields,
dataType: 'json',
success: function(response) {
if(response.status) {
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$('#response').empty().html(response.html);
}
});
grecaptcha.reset();// to reset their widget for any other tries
}
</script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script>
// this block can be defined anywhere
$(function() {
$("#contact-submit").on('click',function() {
// call grecaptcha.execute, which causes recaptcha to
// do its thing and then calls onSubmit with the token
grecaptcha.execute();// does not return anything directly
return false;
});
});
</script>

jquery not getting result from inputs

Why I am not getting values from inputs? I checked it with alert box and there's no values. I do not see any wrong codes or maybe i might have forgotten something to write on my code
<div class="login" align="left">
<input type="input" class="user" placeholder="Username"/>
<input type="password" class="pass" placeholder="Password"/>
<button name="login" class="btnLogin" id="btnLogin">LOGIN</button>
<div class="register">Register Now!</div>
</div>
<script>
$(document).ready(function(){
$(document).on('click','#btnLogin',function(){
var username = $('.user').text();
var password = $('.pass').text();
alert(username); //------------>this alert box is null
$.ajax ({
url:"login_func.php",
method:"POST",
data:{username:username, password:password},
dataType:"text",
success:function(data){
alert(data);
}
});
});
});
</script>
</body>
Use val() and not text()
$('.user').val();
For all kind of input elements , select and textarea you use val() to get its value. And rest elements you use text() to get the inner text of those elements
Value from input fields are normally accessed through .val.
$(document).ready(function(){
$(document).on('click','#btnLogin',function(){
var username = $('.user').val();
var password = $('.pass').val();
alert(username); //------------>this alert box is null
$.ajax ({
url:"login_func.php",
method:"POST",
data:{username:username, password:password},
dataType:"text",
success:function(data){
alert(data);
}
});
});
});
You need to use .val() instead of .text() since you are trying to get a valuye of the input field. .text() should be used for a text element like <div>, <p> etc.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body><div class="login" align="left">
<input type="input" class="user" placeholder="Username"/>
<input type="password" class="pass" placeholder="Password"/>
<button name="login" class="btnLogin" id="btnLogin">LOGIN</button>
<div class="register">Register Now!</div>
</div>
<script>
$(document).ready(function(){
$(document).on('click','#btnLogin',function(){
var username = $('.user').val();
var password = $('.pass').val();
alert(username); //------------>this alert box is null
$.ajax ({
url:"login_func.php",
method:"POST",
data:{username:username, password:password},
dataType:"text",
success:function(data){
alert(data);
}
});
});
});
</script>
</body>
Input does not have to be retrieved by text but by val().
check this snippet.
$(document).ready(function() {
$(document).on('click', '#btnLogin', function() {
var username = $('.user').val();
var password = $('.pass').val();
alert(username); //------------>this alert box is null
$.ajax({
url: "login_func.php",
method: "POST",
data: {
username: username,
password: password
},
dataType: "text",
success: function(data) {
alert(data);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="login" align="left">
<input type="input" class="user" placeholder="Username" />
<input type="password" class="pass" placeholder="Password" />
<button name="login" class="btnLogin" id="btnLogin">LOGIN</button>
<div class="register">Register Now!
</div>
</div>
<script>
</script>
</body>
Hope it helps
use .val() instead of .text() to retrieve values.
and change the input type of user from input to text.i.e.
<input type="text" class="user" placeholder="Username"/>
Change your input type to text for username and use val() instead text()
$(document).ready(function(){
$(document).on('click','#btnLogin',function(){
var username = $('.user').val(); //here you need to use val()
var password = $('.pass').val(); //here you need to use val()
alert(username+ ", "+ password); //------------>this alert box is null
$.ajax ({
url:"login_func.php",
method:"POST",
data:{username:username, password:password},
dataType:"text",
success:function(data){
alert(data);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="login" align="left">
<input type="text" class="user" placeholder="Username"/> <!--here you need to add type text-->
<input type="password" class="pass" placeholder="Password"/>
<button name="login" class="btnLogin" id="btnLogin">LOGIN</button>
<div class="register">Register Now!</div>
</div>

ajax upload file form

I have two forms, one for uploading a file and another for filling the form with information. I need to upload the file without refreshing the page first and then submit the form using ajax. And here are the codes:
form_file
<h1>Insert Employee</h1>
<form id="form">
<input id="name" placeholder="arabic name.." type="text" name="name_ar"/><br>
<input id="name" placeholder="english name.." type="text" name="name_en" value=""/><br>
<input id="name" placeholder="arabic department.." type="text" name="dep_ar" /><br>
<input id="name" placeholder="english department.." type="text" name="dep_en" /><br>
<input id="name" placeholder="arabic job.." type="text" name="job_ar"/><br>
<input id="name" placeholder="english job.." type="text" name="job_en" /><br>
<input id="name" placeholder="extention#.." type="text" name="ext" /><br>
<input id="name" placeholder="office#.." type="text" name="office" /><br>
<input id="name" placeholder="mobile#.." type="text" name="mobile" /><br>
<input id="email" placeholder="email" type="text" name="email"/><br>
<br /><br />
<div class="upload_form">
<form id='form1'>
<input type="file" name="userfile" size="20" />
<input type="button" value="upload" id="upload" />
</form>
<br/><br/>
</div>
<input type="button" value="Click" id="submit"/>
<input type="reset" value="Reset"/>
</form>
</div>
AND HERE IS THE AJAX: I know how to submit data using ajax but I need help for how to upload a file using ajax without refreshing the page, and then take the name of that file, send it again with the form, and save it to database.
<script>
$(document).ready(function(){
$('#upload').click(function(){
console.log('upload was clicked');
//ajax POST
$.ajax({
url:'upload/do_upload',
type: 'POST',
success: function(msg) {
//message from validation php
//append it to the contact_form id
$('#uploud_form').empty();
$('#uploud_form').append(msg);
}
});
return false;
});
$('#submit').click(function(){
console.log('submit was clicked');
//empty msg value
//$('#msg').empty();
//Take form values
var form_data = {
name: $('#name').val(),
email: $('#email').val(),
message: $('#message').val()
};
//ajax POST
$.ajax({
url:'',
type: 'POST',
data: form_data,
success: function(msg) {
//message from validation php
//append it to the contact_form id
$('#contact_form').empty();
$('#contact_form').append(msg);
}
});
return false;
});
});
</script>
Not sure whether I get it properly or not. I will try to answer as per my understanding.
You need to write server side code which will save the image on server.
I believe you are able to make the AJAX call to initiate point 1.
From your upload service (point 1), your should return the "relative path" of the image which was uploaded.
In success callback of your AJAX call (point 2) you should be able to capture the relative path.
Once the relative path has been captured you should add it to DOM or say any element.
Then you can start another AJAX call or post back (submit form) based on your requirement.
If this is not the problem then please be specific in what you need and provide more information.
I do it like this and it's work for me :)
<div id="data">
<form>
<input type="file" name="userfile" id="userfile" size="20" />
<br /><br />
<input type="button" id="upload" value="upload" />
</form>
</div>
<script>
$(document).ready(function(){
$('#upload').click(function(){
console.log('upload button clicked!')
var fd = new FormData();
fd.append( 'userfile', $('#userfile')[0].files[0]);
$.ajax({
url: 'upload/do_upload',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
console.log('upload success!')
$('#data').empty();
$('#data').append(data);
}
});
});
});
</script>

Why does the second form disappear after submiting?

There is the piece of code containing 2 forms:
<form class="emp-delete">
<label for="emp-id">Id:</label>
<input type="text" id="emp-id" />
<input type="submit" id="submit" value="delete" />
<span id="status" />
</form>
<script type="text/javascript">
$("#submit").click(function(){
$.ajax({
type: "DELETE",
url: "/corporate/employees/" + $("#emp-id").val(),
complete: function(r){
$("#status").text(r.responseText);
}
})
return false;
})
</script>
<p><spring:message code="createEmployee.title"/>
<form class="emp-create">
<label for="name" />
<input type="text" id="name" value="create"/>
<input type="submit" id="add-emp" />
</form>
<script type="text/javascript">
$("#add-emp").click(function(){
var employeeObject= { name: $("#name").val() }
$.ajax({
type: "POST",
data: JSON.stringify(employeeObject),
contentType: "application/json",
url: "/corporate/employees"
})
return false;
})
</script>
The issue is after clicking the delete button the second form dissapears.
Before:
After:
How can I do that the second form doesn't dissapear when clicking the delete button.
UPDATE
DEMO
The problem is right here:
<span id="status"/>
Change this to:
<span id="status"></span>
The browser thinks, that the span is openend and your second form is a child of it, which got replaced with your text.

Categories