I'm trying to validate a form before allowing my ajax submission,however I have two problems. The first problem being I don't know how to best go about validating before submission (most professional process). The second problem being, what is preventing my validation code I currently from working? Looking to become more efficient so all input is welcome. Thanks a ton.
$('#form-reg').on('submit', function(){
var bool = false;
var name = document.getElementById('#name-reg');
var email = document.getElementById('#email-reg');
console.log(name);
console.log(email);
if(!/[^a-zA-Z]/.test(name)){
bool = true;
}
else{
bool = false;
}
if(bool == true){
console.log(document.getElementById('#name-reg'));
$('#form-reg').slideUp('slow');
// serialize the form
var formData = $(this).serialize();
console.log(formData);
$.ajax({
type : 'POST',
url : 'register.php',
data : formData,
success: function() {
alert("Success");
},
error: function(xhr) {
alert("fail");
}
})
.done(function (data) {
document.getElementById('form-reg').reset();
})
.fail(function (error) {
alert("POST failed");
});
//return false;
}
else {
alert('try again');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript">
<form id = "form-reg">
<label id ="x" for="name">Name</label>
<input id="name-reg" name="name"></br>
<label id = "y" for="email">Email</label>
<input id="email-reg" name="email"></br>
<input type="submit" value="submit" id = "submit-reg">
</form>
The issue with your code is you have to stop the form submit like:
$('#form-reg').on('submit', function(e){
e.preventDefault();
and after checking the validation, submit the form if validation succeeds.
Although it is a minor answer, I will post it anyway. The problem looks like the use of
var name = document.getElementById('#name-reg');
the # is causing the first problem and should be
var name = $('#name-reg').val();
$('#form-reg').on('submit', function(){
var bool = false;
var name = $('#name-reg').val();
var email = $('#email-reg').val();
console.log(name);
console.log(email);
if(!/[^a-zA-Z]/.test(name)){
bool = true;
}
else{
bool = false;
}
if(bool == true){
console.log($('#name-reg').val());
$('#form-reg').slideUp('slow');
// serialize the form
var formData = $(this).serialize();
console.log(formData);
$.ajax({
type : 'POST',
url : 'register.php',
data : formData,
success: function() {
alert("Success");
},
error: function(xhr) {
alert("fail");
}
})
.done(function (data) {
document.getElementById('form-reg').reset();
})
.fail(function (error) {
alert("POST failed");
});
//return false;
}
else {
alert('try again');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript">
<form id = "form-reg">
<label id ="x" for="name">Name</label>
<input id="name-reg" name="name"></br>
<label id = "y" for="email">Email</label>
<input id="email-reg" name="email"></br>
<input type="submit" value="submit" id = "submit-reg">
</form>
Related
I want to print errors to the screen within a div and keep them there until there is a successful transmission. However this will not allow a submission. I can submit if I remove the e.preventDefault() but then the content of the error div flashes and vanishes. Is there a way to do both?
$("#submitButton").click(function (e)
{
e.preventDefault();
$('#message').hide();
//processing errors
if (errorstr !== "") {
var d;
d = document.getElementById("message");
d.innerHTML = errorstr;
$('#message').show();
}
else {
$('#message').hide();
}
}
#using (Html.BeginForm(...)
{
<div id="message"></div>
<input type="submit" name="submitButton" id="submitButton" class="form-input"/>
}
Either use ajax or URL.Action to submit the form.
ajax way:
function submitForm()
{
$.ajax({
url: 'Controller/Action',
data: { } // your data
}).done(function() {
alert('Success');
});
}
Usage:
if (errorstr !== "") {
var d;
d = document.getElementById("message");
d.innerHTML = errorstr;
$('#message').show();
}
else {
submitForm();
$('#message').hide();
} }
URL.Action way:
window.location.href = '#Url.Action("Action", "Controller")/' + data;
I have a ajax call I want to use on a form so the user doesn't have to reload the page but it just keeps loading. I have tried to change the post route but I haven't had any success. Can someone point me in the right direction. Here is my code:
HTML
const http = new XMLHttpRequest();
const submit = document.querySelector('.submit');
http.onload = () => {
submit.addEventListener('click', () =>{
const alertMessage = document.querySelector('.alert');
const email = document.querySelector('#email').value;
const name = document.querySelector('.name').value;
if (name === '' || email === '') {
alertMessage.innerHTML = 'Name And Email Required';
console.log(name)
} else {
alertMessage.innerHTML = 'Success! Someone will be in touch with you soon!'
// email.value = '';
// form.reset();
}
});
}
http.open('POST', '/index.html', true);
http.send();
FORM
<div class="contactform">
<div class="alert"></div>
<form action="/index.html" method="POST" class="form">
<input type="text" name='name' id='name' placeholder="Name">
<input type="email" name='email' id='email' placeholder="Email">
<textarea class="messages" name="messages" placeholder="Message...."></textarea>
<button class="submit" type="submit" value="submit">Send</button>
</form>
</div>
You need to override form's onsubmit event to prevent submitting:
$("formSelector").bind('submit', function (e) {
var isValid = someYourFunctionToCheckIfFormIsValid();
if (!isValid) {
e.preventDefault();
return false;
} else {
jQuery.ajax({
type: "POST",
url: "my_custom/url",
dataType: "html",
data: { "text": jQuery("#edit-body").html()
},
success: function (result) {
console.log(result);
}
});
e.preventDefault();
return false;
}
});
By calling
e.preventDefault();
return false;
You prevent synchronous postback from occurring.
UPDATE:
If you don't want to override form submit, maybe you could place your button outside of form tag (you can adjust position with css if necessary)?
I am trying to insert more than one data in db using js ajax but it is not working and when i am trying to inserting only one data it is successfully working
Here is my indexa.php
<html>
<head>
<script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActionXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('success_failed_msg').innerHTML = xmlhttp.responseText;
} else {
console.log("faliled");
}
}
parameters = 'first_name='+document.getElementById('firstName').value;
console.log(parameters);
xmlhttp.open('POST','insert.inc.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameters);
}
</script>
</head>
<body>
First Name : <input type="text" id="firstName"><br/><br/>
Last Name : <input type="text" id="lastName"><br/><br/>
Username : <input type="text" id="userName"><br/><br/>
Password : <input type="password" id="password"><br/><br/>
Re-type Password : <input type="password" id="retypePassword"><br/><br/>
<input type="button" value="Submit" onclick="insert()">
<div id="success_failed_msg"></div>
</body>
</html>
My include.inc.php
if (isset($_POST['first_name'])) {
$firstname = $_POST['first_name'];
if (!empty($firstname)) {
$insert_select = "INSERT INTO ajax_member_data(`first_name`) VALUES('".mysqli_real_escape_string($db_connect,$firstname)."')";
if ($insert_query_run = mysqli_query($db_connect,$insert_select)) {
echo 'Data inserted successfully';
} else {
echo 'Failed';
}
} else {
echo 'Please enter the value';
}
}
and when I am trying this script it
<script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else{
xmlhttp = new ActionXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('success_failed_msg').innerHTML = xmlhttp.responseText;
} else {
console.log("faliled");
}
}
parameters = 'first_name='+document.getElementById('firstName').value'&last_name='+document.getElementById('lastName').value'&username='+document.getElementById('userName').value'&password='+document.getElementById('password').value'&retype_password='+document.getElementById('retypePassword').value;
console.log(parameters);
xmlhttp.open('POST','insert.inc.php',true);
xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xmlhttp.send(parameters);
}
</script>
my include.inc.php
if (isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['username']) && isset($_POST['password']) && isset($_POST['retype_password'])) {
$firstname = $_POST['first_name'];
$lastname = $_POST['last_name'];
$usrname = $_POST['username'];
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if (!empty($firstname) && !empty($lastname) && !empty($usrname) && !empty($password) && !empty($retype_password)) {
$insert_select = "INSERT INTO ajax_member_data(`first_name`,`last_name`,`user_name`,`password`) VALUES('".mysqli_real_escape_string($db_connect,$firstname)."', '".mysqli_real_escape_string($db_connect,$lastname)."', '".mysqli_real_escape_string($db_connect,$usrname)."', '".mysqli_real_escape_string($db_connect,$password)."')";
if ($insert_query_run = mysqli_query($db_connect,$insert_select)) {
echo 'Data inserted successfully';
} else {
echo 'Failed';
}
} else {
echo 'Please enter the value';
}
}
You haven't done concatenation properly. See here,
parameters = 'first_name='+document.getElementById('firstName').value'&last_name='+document.getElementById('lastName').value'&username='+document.getElementById('userName').value'&password='+document.getElementById('password').value'&retype_password='+document.getElementById('retypePassword').value;
^ missing + ^ missing + ^ missing + ^ missing +
It should be,
parameters = 'first_name='+document.getElementById('firstName').value+'&last_name='+document.getElementById('lastName').value+'&username='+document.getElementById('userName').value+'&password='+document.getElementById('password').value+'&retype_password='+document.getElementById('retypePassword').value;
Sidenote: Learn about prepared statements because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.
You are missing plus(+) sign while passing parameter. Please change your code as below:
Old Code:
parameters = 'first_name='+document.getElementById('firstName').value'&last_name='+document.getElementById('lastName').value'&username='+document.getElementById('userName').value'&password='+document.getElementById('password').value'&retype_password='+document.getElementById('retypePassword').value;
New Code:(Added plus(+) sign wherever it was required)
parameters = 'first_name='+document.getElementById('firstName').value + '&last_name='+document.getElementById('lastName').value + '&username='+document.getElementById('userName').value + '&password='+document.getElementById('password').value + '&retype_password='+document.getElementById('retypePassword').value;
If you wrap the input fields with a form and use jQuery serialize could be easier.
Example HTML:
<form>
First Name : <input type="text" id="firstName"><br/><br/>
Last Name : <input type="text" id="lastName"><br/><br/>
Username : <input type="text" id="userName"><br/><br/>
Password : <input type="password" id="password"><br/><br/>
Re-type Password : <input type="password" id="retypePassword"><br/><br/>
<input type="button" value="Submit">
<div id="success_failed_msg"></div>
</form>
Example JS:
//you can use the var sending to avoid
// more than one request at the same time
var sending = false;
$('form').on('submit', function(ev){
ev.preventDefault();
if (!sending) {
$.ajax({
url: 'insert.inc.php',
method: 'post',
dataType: 'json',
data: $('form').serialize(),
cache: false,
beforeSend: function() {
//here you can show an ajax loading icon
sending = true;
},
success: function(response){
//here you can show a success message and check if the
//response is correct
//response object depends on the server side response
if (response.success || response.success === 'true') {
//show success message...
} else {
//show error message...
}
},
error: function(err){
//here you can show an error message
},
complete: function(){
//here you can hide the ajax loading icon
sending = false;
}
});
}
});
Documentation from jQuery:
Ajax http://api.jquery.com/jquery.ajax/
Serialize https://api.jquery.com/serialize/
And you can format a json response from the server side
json_encode (with this you "transform" a php array to a js object) http://php.net/manual/en/function.json-encode.php
header('Content-Type: application/json'); with this the app will know what type of response is given
You can read more about json and ajax here:
http://www.json.org/
https://developer.mozilla.org/en-US/docs/AJAX
And a tutorial about how to see the request on Firefox: https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor
And on Chrome: https://developers.google.com/web/tools/chrome-devtools/network-performance/resource-loading
var sending = false;
$('form').on('submit', function(ev){
ev.preventDefault();
if (!sending) {
$.ajax({
url: 'insert.inc.php',
method: 'post',
dataType: 'json',
data: $('form').serialize(),
cache: false,
beforeSend: function() {
console.log("processing");
sending = true;
},
success: function(response){
if (response.success || response.success === 'true') {
('#success_failed_msg').text(response);
} else {
('#success_failed_msg').text('response failed');
}
},
error: function(err){
('#success_failed_msg').text(err);
},
complete: function(){
console.log('process complete');
sending = false;
}
});
}
});
I have created a simple form consisting of a textarea field, so when user clicks on submit button its linked to a jquery script containing a url executing the process and store the data, but problem is every time i hit submit, ID & created_at data is stored but the data given on textarea is ignored and not stored, never faced this problem before..please help me out!
HTML
<form id="form" name="form" method="POST" action="profile_1.php" class="wizard-big" autocomplete="off" enctype="multipart/form-data" required="">
<div class="form-group col-sm-12">
<textarea type="text" name="status" id="status" placeholder="What's on your mind.." class="form-control" style="height:100px;"></textarea>
</div>
<div class="col-sm-12 form-group">
<input style="width:100%" type="submit" name="submit" id="submit" value="Post" class="btn btn-success">
</div>
</form>
Jquery
$(document).ready(function() {
$("#submit").click(function(e) {
var status = $('form')[0].checkValidity();
if (status) {
var formData = new FormData($('form')[0]);
$.ajax({
url: "form_post.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
async: false,
dataType: "JSON",
success: function(json) {
if (json.error) {
alert(json.error_msg);
e.preventDefault();
} else {
alert("Post updated successfully!");
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
});
});
php
<?php
session_start();
define('HOST','localhost');
define('USER','**');
define('PASS','**');
define('DB','**');
$response = array();
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
if(!mysqli_connect_errno()){
$error_flag = false;
/*foreach($_POST as $value){
if(empty($value)){
$error_flag = true;
break;
}
}*/
if(!$error_flag){
//receiving post parameters
$status =$_POST['status'];
// create a new user profile
$sql = "INSERT INTO status (via, status, created_at) VALUES ('".$_SESSION['vault_no']."', '$status', NOW())";
if(mysqli_query($con,$sql)){
$response["error"] = false;
$response['via'] = $via;
echo json_encode($response);
}else{
$response["error"] = true;
$response["error_msg"] = "INSERT operation failed";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Few fields are missing";
echo json_encode($response);
}
}else{
$response["error"] = true;
$response["error_msg"] = "Database connection failed";
echo json_encode($response);
}
?>
Note: The solution is in the comments for other readers of this question
Maybe this helps you out. You need to change it to your wish offcourse
And save this function, it could be usefull for you in the future.
This function serializes the form as how it should be done.
<script>
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form').submit(function() {
var formData = $('form').serializeObject();
$.ajax({
data: formData,
type: 'POST',
url: 'form_post.php',
success: function(result) {
$('#result').html(result);
},
error: function(jqXHR, textStatus, errorThrown) { alert(textStatus); }
});
return false;
});
});
</script>
i have a live chat messaging system whenever user press enter button it refreshes the page i have tried using prevent default code also but did not worked for me.... here is the code and if there is any problem in the below code please let me know as i'm totally new to website programming
jQuery(document).ready(function() {
jQuery('.btn-success').click(function() {
var form_name = jQuery(this).attr('title');
var obj = jQuery(this);
jQuery(".ajax_indi").show();
switch (form_name) {
case "npost":
var message = jQuery("#message").val();
break;
default:
alert("something went wrong!");
}
if((jQuery(message) == ''))
{
alert("Message Cannot be Empty");
jQuery(".ajax_indi").hide();
return false;
} else {
jQuery(this).attr("disabled", "disabled");
jQuery(this).prop('value', 'Loading...');
jQuery(this).css('cursor', 'default');
}
var str = jQuery("#"+form_name).serialize();
jQuery.ajax({
type: "POST",
url: "chat.php",
data: str,
cache: false,
success: function(html){
jQuery('#chat1').append(html);
obj.attr("disabled", false);
obj.prop('value', 'Post');
obj.css('cursor', 'pointer');
jQuery(".ajax_indi").hide();
document.getElementById(form_name).reset();
}
});
});
});
Edited part
<form id="npost" name="npost">
<input class="form-control" placeholder="Type your message here..."
type="text" name="message">
<input type="hidden" name="id" value="1">
<span class="input-group-btn">
<button type="button" class="btn btn-success" title="npost" >Send</button>
if you want to prevent from submitting the form you can use return false if you want to stop executing the function and stop submitting it
You need to use preventDefault in order to stop form submission on clicking enter because by default form gets submitted when anyone presses enter. So use preventDefault like this:
<script type="text/javascript" >
jQuery(document).ready(function(){
jQuery('.btn-success').click(function(e){ // added e
e.preventDefault(); // added this line
var form_name = jQuery(this).attr('title');
var obj = jQuery(this);
jQuery(".ajax_indi").show();
var message = '';
switch (form_name)
{
case "npost":
var message = jQuery("#message").val();
break;
default:
alert("something went wrong!");
}
if((jQuery(message) == ''))
{
alert("Message Cannot be Empty");
jQuery(".ajax_indi").hide();
return false;
} else {
jQuery(this).attr("disabled", "disabled");
jQuery(this).prop('value', 'Loading...');
jQuery(this).css('cursor', 'default');
}
var str = jQuery("#"+form_name).serialize();
jQuery.ajax({
type: "POST",
url: "chat.php",
data: str,
cache: false,
success: function(html){
jQuery('#chat1').append(html);
obj.attr("disabled", false);
obj.prop('value', 'Post');
obj.css('cursor', 'pointer');
jQuery(".ajax_indi").hide();
document.getElementById(form_name).reset();
}
});
});
});
</script>
Here You should not stop form default action you to prevent enter key default answer here is the code to prevent.
$('#npost').on('keyup keypress', function(e) {
if (e.which== 13) {
e.preventDefault();
return false;
}
});