jquery ajax prevent form submit if username is unavailable - javascript

i am using this script to check username availability, it works but the form is submitted even if the username is unavailable. i tried to use event.preventdefault but, i don't know to use it correctly how can i prevent the form to be submitted?
<script>
function checkAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data: 'username=' + $("#username").val(),
type: "POST",
success: function(data) {
$("#user-availability-status").html(data);
$("#loaderIcon").hide();
},
error: function() {}
});
}
</script>
here is the form
<form id="defaultForm" action="index1.php" method="post" class="registration-form">
Username
<br>
<input type="text" name="username" onBlur="checkAvailability()" id="username">
<br><span id="user-availability-status"></span> Password
<br>
<input type="text" name="email" id="email">
<br>
<button type="submit" name="sub">Submit</button>
here is check_availability.php
<?php
require_once("connect.php");
if(!empty($_POST["username"])) {
$result = mysqli_query($con,"SELECT count(*) FROM users WHERE username='" . $_POST["username"] . "'");
$row = mysqli_fetch_row($result);
$user_count = $row[0];
if($user_count>0) {
echo "<span class='status-not-available'><p style='text-align:center'> Username Not Available</p></span>";
}
}
?>

Remove the function call in your HTML
$(document).ready(function(){
$("#defaultForm").submit(function(e) {
e.preventDefault();
$("#loaderIcon").show();
var self = this;
$.ajax({
url: "check_availability.php",
data: 'username=' + $("#username").val(),
type: "POST"
}).success(function(data) {
$("#user-availability-status").html(data);
$("#loaderIcon").hide();
if (data!= "<span class='status-not-available'><p style='text-align:center'> Username Not Available</p></span>")
self.submit();
}).error(function() {
alert('error');
});
});
});

Related

ajax in codeigniter showing only false message even when the value exist in database

I am trying to check if value exist in database in my CodeIgniter website using AJAAX. I have written the following code:
<input id="username" name="pincode" type="text" class="form-control" placeholder="Enter Pincode">
<input id="prodid" name="prodid" value="<?php echo $prodid;?>" type="hidden">
<button type="button" onclick="check_if_exists();" class="btn btn-primary">Check</button>
function check_if_exists() {
var username = $("#username").val();
var prodid = $("#prodid").val();
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>index.php/homecontroller/filename_exists",
data: {
username: username,
prodid: prodid
},
success: function(response) {
if (response == true) {
$('#msg').html('<span style="color: green;">' + msg + "</span>");
} else {
$('#msg').html('<span style="color:red;">Delivery Not Available at ' + username + '</span>');
}
}
});
}
function filename_exists()
{
$username = $this->input->post('pincode');
$prodid = $this->input->post('prodid');
$exists = $this->product->filename_exists($prodid);
if ($exists) {
return true;
} else {
return false;
}
}
function filename_exists($prodid)
{
$this->db->select('*');
$this->db->where('id', $prodid);
$this->db->from('product');
$query = $this->db->get();
$result = $query->result_array();
return $result;
}
I am only getting the message that the value doesn't exist even if the value is there in database.
You are using AJAX not the form submission method, so in back-end post() method won't work
To transfer a value from server in php, one method is echo, but return is wrong here.
Please rewrite your code like this
View
function check_if_exists() {
var username = $("#username").val();
var prodid = $("#prodid").val();
var transfer = [username,prodid];
$.ajax({
type: "post",
url: "<?php echo base_url(); ?>index.php/homecontroller/filename_exists",
data: {result: JSON.stringify(transfer)},
success: function(response) {
if (response) {
$('#msg').html('<span style="color: green;">' + msg + "</span>");
} else {
$('#msg').html('<span style="color:red;">Delivery Not Available at ' + username + '</span>');
}
}
});
}
Controller
function filename_exists()
{
$post = json_decode($_POST['result']);
$username = $post[0];
$prodid = $post[1];
$exists = $this->product->filename_exists($prodid);
echo $exists;
}
Modal
function filename_exists($prodid)
{
$this->db->select('id');
$this->db->where('id', $prodid);
$this->db->from('product');
$query = $this->db->get();
if($query->num_rows()) return true;
}
enter code here

Getting data back from a PHP script

So after validating the form via Jquery, I like to know if the username and password are valid. If they are, it should redirect to another page, else I want to find a way of showing it to the user. At this point, I'm really confused. Here's the jquery code:
$(document).ready(function(e) {
$('.error').hide();
$('#staffLogin').submit(function(e) {
e.preventDefault();
$('.error').hide();
uName = $('#staff_username').val();
pWord = $('#staff_password').val();
if(uName == ''){
$('#u_error').fadeIn();
$('#staff_username').focus();
return false;
}
if(pWord == ''){
$('#p_error').fadeIn();
$('#staff_password').focus();
return false;
}
$.ajax({
type : 'POST', url : 'staff_access.php', data : 'uName='+uName+'&pWord='+pWord,
success: function(html){
if(html == 'true'){
window.location = 'staff_page.php';
}
else{
$('#val_error').fadeIn();
}
}
})
});
});
PHP:
<?php
include('admin/config.php');
$username = $_POST['uName'];
$password = $_POST['pWord'];
$conn = mysqli_connect(DB_DSN,DB_USERNAME,DB_PASSWORD,dbname);
if ($conn) {
$qry = "SELECT lastname, firstname, FROM staff_user WHERE username='".$username."' AND pass='".$password."";
$res = mysqli_query($qry);
$num_row = mysqli_num_rows($res);
$row=mysql_fetch_assoc($res);
if ($num_row == 1) {
session_start();
$_SESSION['login'] = true;
$_SESSION['lastname'] = $row['lastname'];
$_SESSION['firstname'] = $row['firstname'];
$_SESSION['username'] = $row['username'];
echo "true";
}
else{
echo "false";
}
}
else{
$conn_err = "Could not connect.".mysql_error();
}
mysqli_close($conn);
?>
FORM:
<form name="staff_login" method="post" action="" id="staffLogin">
<fieldset>
<legend>Staff Login</legend>
<span class="fa fa-user fa-5x"></span>
<br><br>
<input type="text" name="staff_username" id="staff_username" placeholder="Username">
<br><span class="error" id="u_error">Username Required</span><br>
<input type="password" name="staff_password" id="staff_password" placeholder="Password">
<br><span class="error" id="p_error">Password Required</span><br>
<span class="error" id="val_error">Incorrect Username and Password combination</span>
<input type="submit" name="staff_login" value="Login">
</fieldset>
</form>
Your ajax data is sent in wrong format. POST data should be sent as an object.
$.ajax({
type : 'POST',
url : 'staff_access.php',
data : {
uName: uName,
pWord: pWord
},
dataType: 'text',
success: function(html){
if(html == 'true'){
window.location = 'staff_page.php';
}
else{
$('#val_error').fadeIn();
}
}
});
Also avoid using texts like 'html'. You may end up getting unnecessary errors due to that.
Use more relevant words like "success: function(response)"
Try to define a dataTpe in your ajax config - dataType: "html"

jquery.ajax, success and done function is not returning anything

I am a wordpress user and try to update the database using jquery.ajax. My code updates the database but the success function doesn't return anything to html div tag. Here are some portions of my code:
PHP Code:
$connect = mysqli_connect(HOST, USER, PASS, NAME);
if(mysqli_connect_errno()){
$msg = "Connection With Database is not Successful. Error: ".mysqli_error();
echo $msg;
die();
}
$nam = $_POST['name'];
$eml = $_POST['email'];
$entry = "INSERT INTO `table` (name, email,) VALUES ('$nam', '$eml')";
if(!mysqli_query($connect, $entry)){
$msg = "Error while submitting Your Data. Error: ".mysqli_error();
echo $msg;
die();
}
$msg = "Your data submitted successfully";
echo $msg;
mysqli_close($connect);
?>
HTML Code:
<form method="POST" id="data_form">
<input type="text" name="name" id="name" placeholder="Full Name" />
<br>
<input type="email" name="email" id="email" placeholder="Email Address" required />
<br>
<button type="submit" id="submit">Submit</button>
</form>
<div id="output"></div>
jQuery Code:
jQuery(document).ready(function (){
$("#data_form").submit(function (e){
e.preventDefault();
var formdata = $("#data_form").serialize();
$.ajax({
type: "POST",
url: "udata.php",
data: formdata,
cache: false,
success: function(result){
$("#output").html(result);
}
});
});
});
I also used 'done' instead of 'success' but didn't work.
jQuery(document).ready(function (){
$("#data_form").submit(function (e){
e.preventDefault();
var formdata = $("#data_form").serialize();
$.ajax({
type: "POST",
url: "udata.php",
data: formdata,
cache: false
}).done(function(result){
$("#output").html(result);
});
});
});
Actually I am trying to print the $msg variable from the php file to the 'output' div tag.
Any help would be greatly appreciated.

jQuery Ajax not working with $.ajax()

I am trying use for fetching data and displaying it through jQuery. This is my script
<script>
$("#kys_SignUp_form").submit(function(event){
event.preventDefault();
var $form = $(this);
var $url = $form.attr('action');
var $email = $("#email").val();
var $username = $("#username").val();
var $password = $("#password").val();
$.ajax({
type: 'POST',
url: $url,
data: { email: $email, password: $password, username: $username },
success: function(data) {
alert("Transaction Completed!");
}
});
});
</script>
And this is my form:
<form role="form" action="kys_SignUp.php" method="post" id="kys_SignUp_form">
<div class="form-group">
<label for="email" >Email address:</label>
<input type="email" style="width: 300px" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<label for="Username" >Username:</label>
<input type="text" style="width: 300px" class="form-control" name="username" id="Username" required>
</div>
<div class="form-group">
<label for="password" >Password:</label>
<input type="password" style="width: 300px" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
I am new to jQuery. The problem that I am facing is the page is being redirected to the php file even after using ajax, I think ajax function is not at all called.
This is my php file:
<?php
include "kys_DbConnect.php";
$email = $username = $password = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = cleanData($_POST["email"]);
$username = cleanData($_POST["username"]);
$password = cleanData($_POST["password"]);
}
$stmt = $con->prepare("SELECT * FROM kys_users WHERE username=? OR email=?");
$stmt->bind_param("ss",$username,$email);
$stmt->execute();
$stmt->bind_result($kys_id,$kys_email,$kys_username,$kys_password);
$stmt->fetch();
if(isset($kys_username)){
echo "Username or Email already exists";
}
else{
$insert = $con->prepare("INSERT INTO kys_users (username, email, password) VALUES (?, ?, ?)");
$insert->bind_param("sss",$username,$email,$password);
$insert->execute();
header("Location: http://localhost/KeyStroke/index.html");
exit();
}
function cleanData($data){
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
I am not able find out what's wrong with my code.
Updated try this :
<form role="form" action="kys_SignUp.php" method="post" id="kys_SignUp_form">
<div class="form-group">
<label for="email" >Email address:</label>
<input type="email" style="width: 300px" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<label for="Username" >Username:</label>
<input type="text" style="width: 300px" class="form-control" name="username" id="Username" required>
</div>
<div class="form-group">
<label for="password" >Password:</label>
<input type="password" style="width: 300px" class="form-control" id="password" name="password" required>
</div>
<button id="submit_btn" class="btn btn-default">Submit</button>
</form>
UPDATED 2 :
<script>
$(function() {
// Handler for .ready() called.
$("#submit_btn").on('click',function(event){
//alert is not being called at all . That means .submit() is never beign called
alert("hello there");
event.preventDefault();
var form = $('#kys_SignUp_form'); //changed from $(this)
var url = form.attr('action');
var email = $("#email").val();
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type: 'POST',
url: url,
dataType:"json", //<-- add this
data: { email: email, password: password, username: username },
success: function(data) {
if(data.success){
window.location.href=data.result;
}else {
alert("ERROR. "+data.result);
}
}
});
});
});
</script>
and in your PHP code
<?php
include "kys_DbConnect.php";
$email = $username = $password = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = cleanData($_POST["email"]);
$username = cleanData($_POST["username"]);
$password = cleanData($_POST["password"]);
}
$stmt = $con->prepare("SELECT * FROM kys_users WHERE username=? OR email=?");
$stmt->bind_param("ss",$username,$email);
$stmt->execute();
$stmt->bind_result($kys_id,$kys_email,$kys_username,$kys_password);
$stmt->fetch();
if(isset($kys_username)){
echo json_encode(array("success"=>false,"result"=>"Username or Email already exists"));
}
else{
$insert = $con->prepare("INSERT INTO kys_users (username, email, password) VALUES (?, ?, ?)");
$insert->bind_param("sss",$username,$email,$password);
$insert->execute();
echo json_encode(array("success"=>true,"result"=>"http://localhost/KeyStroke/index.html"));
}
function cleanData($data){
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<script>
$("#clickbutton").click(function(){
var $url = 'kys_SignUp.php';
var $email = $("#email").val();
var $username = $("#Username").val();
var $password = $("#password").val();
$.ajax({
type: 'POST',
url: $url,
data: 'email='+$email+'&password='+$password+'&username='+$username,
success: function(data) {
alert("Transaction Completed!");
}
});
});
</script>
and also remove action in your form and change your submit button
<button type="button" id="clickbutton" class="btn btn-default">Submit</button>
Try this function:
<script>
$(function() {
$('#kys_SignUp_form button[type="submit"]').on('click',function(event){
alert("hello there");
event.preventDefault();
var form = $("#kys_SignUp_form");//note here we select the form element to get the url
var url = form.attr('action');
var email = form.find("#email").val();
var username = form.find("#username").val();
var password = form.find("#password").val();
$.ajax({
type: 'POST',
url: url,
dataType:"json",
data: { email: email, password: password, username: username },
success: function(data) {
if(data.message == "Success") {
window.location ='http://localhost/KeyStroke/index.html';
} else {alert(data.message)}
});
});
});
</script>
php:
include "kys_DbConnect.php";
function cleanData($data){
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function isUser($username,$email)
$stmt = $con->prepare("SELECT * FROM kys_users WHERE username=? OR email=?");
$stmt->bind_param("ss",$username,$email);
$stmt->execute();
$stmt->bind_result($kys_id,$kys_email,$kys_username,$kys_password);
$stmt->fetch();
if(isset($kys_username)){
return true;
}
}
function inserNewUser($username,$email,$password)
$insert = $con->prepare("INSERT INTO kys_users (username, email, password) VALUES (?, ?, ?)");
$insert->bind_param($username,$email,$password);
$insert->execute();
}
if($_SERVER["REQUEST_METHOD"] == "POST"){
$email = cleanData($_POST["email"]);
$username = cleanData($_POST["username"]);
$password = cleanData($_POST["password"]);
if (isUser($username,$email)) {
echo json_encode(['message'=>'Username or Email already exists'])
} else {
inserNewUser($username,$email,$password);
echo json_encode(['message'=>'Success']);
}
} else {
echo json_encode(['message'=>'Error get method not allowed'])
}
Look at my way, may be it will help you.
$('#frmReportWithparams').submit(function () {
$.ajax({
url: "#Url.Content("~/LeftMenu/SendReportWithParameter")",
type: "POST",
data: $('#frmReportWithparams').serialize(),
success: function (result) {
if (result.IsSuccess == true) {
alert("Thank You.")
$('#modalHomeIndex').dialog('close')
}
else {
alert("'Error Occurs.Try Later.")
$('#modalHomeIndex').dialog('close')
}
}
})
return false;
})
actually the code is for C#, but i just set where to post a form in ajax.
look at #Url.content where i passed the values where my form will be posted.
and the parameters are serialized in data field.
if you have any other query then ask further...
Why Use $ in js variable this is wrong.
Use This One.
var form = $(this);
var url = $form.attr('action');
var email = $("#email").val();
var username = $("#username").val();
var password = $("#password").val();
try this may be this will work
<script>
$(document ).ready(function() {
$('#kys_SignUp_form').on('submit', function(e) {
e.preventDefault();
});
});
// ================ SUBMIT =====================
$('#kys_SignUp_form .form_submit').on('click', function(e){
e.preventDefault();
var $form = $(this);
var $email = $("#email").val();
var $username = $("#username").val();
var $password = $("#password").val();
$.ajax({
type: 'POST',
url: 'kys_SignUp.php',
dataType: 'json',
data: { email: $email, password: $password, username: $username },
success: function(data) {
alert("Transaction Completed!");
},
error : function( errorThrown) {
alert('errorThrown ' + errorThrown);
}
});
});
</script>
HTML
<form role="form" method="post" id="kys_SignUp_form">
<div class="form-group">
<label for="email" >Email address:</label>
<input type="email" style="width: 300px" class="form-control" name="email" id="email" required>
</div>
<div class="form-group">
<label for="Username" >Username:</label>
<input type="text" style="width: 300px" class="form-control" name="username" id="Username" required>
</div>
<div class="form-group">
<label for="password" >Password:</label>
<input type="password" style="width: 300px" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-default form_submit">Submit</button>
You need to do two things.
1- Change var var url = $form.attr('action'); to
var url = $("#kys_SignUp_form").attr('action');
2- Add a return statement just before you submit function ends
complete script will look like below-
<script>
$( document ).ready(function() {
// Handler for .ready() called.
$("#kys_SignUp_form").submit(function(event){
alert("hello there");
event.preventDefault();
var form = $(this);
var url = $("#kys_SignUp_form").attr('action');
var email = $("#email").val();
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type: 'POST',
url: url,
data: { email: email, password: password, username: username },
success: function(data) {
alert("Transaction Completed!");
}
});
return false;
});
});
</script>

Ajax form submission inside modal box

Ok here is a strange little problem:
Here is a test page, which user clicks to open:
When user clicks view results I have 3 selectboxes inside the modal box.
box1 => populates =>Box 2 => populates Box 3
My problem
When user clicks submit, instead of results being displayed from the query based on selectbox selections, the test page opens again inside the modalbox... as you can see in below image
On submit
Any idea why when form is submitted current page opens inside modalbox?
Submit Form
<script type="text/javascript">
jQuery(document).click(function(e){
var self = jQuery(e.target);
if(self.is("#resultForm input[type=submit], #form-id input[type=button], #form-id button")){
e.preventDefault();
var form = self.closest('form'), formdata = form.serialize();
//add the clicked button to the form data
if(self.attr('name')){
formdata += (formdata!=='')? '&':'';
formdata += self.attr('name') + '=' + ((self.is('button'))? self.html(): self.val());
}
jQuery.ajax({
type: "POST",
url: form.attr("action"),
data: formdata,
success: function(data) { $('#resultForm').append(data); }
});
}
});
</script>
Populate Textboxes
<script type="text/javascript">
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
<label>Sport :</label>
<form method="post" id="resultForm" name="resultForm" action="result.php">
<select name="sport" class="sport">
<option selected="selected">--Select Sport--</option>
<?php
$sql="SELECT distinct sport_type FROM events";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result))
{
?>
<option value="<?php echo $row['sport_type']; ?>"><?php echo $row['sport_type']; ?></option>
<?php
}
?>
</select>
<label>Tournamet :</label> <select name="tournament" class="tournament">
<option selected="selected">--Select Tournament--</option>
</select>
<label>Round :</label> <select name="round" class="round">
<option selected="selected">--Select Round--</option>
</select>
<input type="submit" value="View Picks" name="submit" />
</form>
<?php
Display result
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo $sport=$_POST['sport'];
echo $tour=$_POST['tournament'];
echo $round=$_POST['round'];
$sql="Select * FROM Multiple_Picks WHERE tournament ='$tour' AND round='$round' GROUP BY member_nr";
$result = mysql_query($sql);
?>
<?php
while($row=mysql_fetch_array($result)){
$memNr = $row['member_nr'];
$pick = $row['pick'];
$score = $row['score'];
?>
echo $memNr;
echo $pick;
echo $score;
}
}
?>
It would appear that:
success: function(data) { $('#resultForm').append(data); } you are telling it to put the ajax response in the resultForm, which appears to be inside your modal. Is that not what is happening. Hard to tell from your question and code what SHOULD be happening vs what IS happening now.

Categories

Resources