In jquery form validation ajax not responding - php

I am trying to validate my code with jquery. Its working but when it come to ajax it not loading any page. Rather my path is wrong or something other. Please help me to solve this.
this is my view file
admin_view.php
<?php include('assets/header.php'); ?>
<div class="container">
<h1>Welcome to Admin Login</h1>
<?if($this->session->flashdata('flashError')):?>
<p class='flashMsg flashError'>
<?= $this->session->flashdata('flashError') ?> </p>
<?endif?>
<!-- new line inserted -->
<form method="post" name="myForm" accept-charset="utf-8" class="login" id="form" >
<div class="form-group">
<div class="col-xs-4">
<!--<label for="admin">Admin</label>
<input type="text" name="admin" class="form-control" id="admin" value="" placeholder="admin name" />-->
Admin Name: <input type="text" name="admin" id="admin" class="form-control" value="<?php echo set_value('admin'); ?>" placeholder="admin name" >
<?php echo form_error("admin"); ?>
<p id='p1'></p>
<br>
<!-- <label for="password">password</label>
<input type="text" name="password" class="form-control" id="password" value="" placeholder="password" required/>
-->
Admin Password: <input type="password" name="password" id="password" class="form-control" value="" placeholder="password" >
<?php echo form_error("password"); ?>
<p id='p2'></p>
<br>
<br>
<input type="button" name="submit" value="submit" id="submit" class="btn btn-primary" >
</div>
</div>
<div class="error"></div>
</form>
</div>
<script>
$(document).ready(function () {
$("#submit").click(function () {
var admin = $("#admin").val();
var password = $("#password").val();
$("#returnmessage").empty(); // To empty previous error/success message.
// Checking for blank fields.
if (admin == '')
{
$('div.error').html("Please Fill Admin Required Fields");
} else if (password == '')
{
$('div.error').html("Please Fill Password Required Fields");
} else
{//alert('hello world');
// Returns successful data submission message when the entered information is stored in database.
$.ajax({
type: "POST",
url: "<?php base_url() ?>index.php/admin_login/login",
data: {"admin": admin, "password": password},
dataType: "json"
}).done(function (data) {
if (data.error != "")
{
//alert('hello if');
$('div.error').html(data.error);
} else
{
// alert('hello else');
window.location.href="admin_view";
}
});
}
});
});
</script>
<?php include('assets/footer.php'); ?>

You have provide wrong path to ajax url,
url: "<?php base_url() ?>index.php/admin_login/login"
this statement will not works directly, because <?php base_url() ?> is a php statement and you are using this in javascript, this is not acceptable.
use like this:
<script type="text/javascript">var path= "<?php echo base_url();?>";</script>
Write this statement in your head section,this statement will define your base url to path variable, which is a javascript variable and you can use it in your javascript code.
then append url like:
url: path+"/index.php/admin_login/login",
hope this will help to you.

Related

Using 2 recaptcha on same page and getting different values for both via AJAX

I have 2 Google Recaptcha's on same page in different forms (Login and Register Forms). I had to put both the forms on the same page due to the designing requirements which can't be changed. Now the problem is that the 1st form is the login form followed by the register form in the 2nd. Now, the recaptcha on the login form takes effect for register form as well. I mean that I can see recaptcha on both the forms but the one in register form doesn't work (which means it doesn't sends the correct value to the PHP page where the form will be processed). When I tried verifying the recaptcha on the login form and submitting the register form it worked. This means that the 1st loaded recaptcha (on the login form) is working for both which should not be. Both the recaptchas should work separately for each forms. Also, when I get the values of both the recaptchas via AJAX to send to the PHP page for the server side validation I am using captcha: grecaptcha.getResponse() for both. THIS CAN BE THE ACTUAL PROBLEM I GUESS. If I could get separate values for both maybe the things would have gone down well. Any help would be appreciated.
Here are my codes.
<div class="container">
<div class="row">
<div class="col-md-6">
<h3 class="com-reps cr-panel">Login Now</h3>
</div>
<div class="col-md-6">
<h3 class="com-reps cr-panel">Register Now</h3>
</div>
<div class="col-md-6">
<div class="post-holder">
<div class="login-message"></div>
<div class="post-content">
<form method="post" action="">
<div class="form-group">
<input type="text" id="uname" class="form-control" placeholder="Username">
</div>
<div class="form-group">
<input type="password" id="pass" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="<?php echo $mainf['set_recaptcha_sitekey']; ?>"></div>
</div>
<div class="form-group">
<input type="submit" id="login" value="Log In" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
<div class="col-md-6">
<div class="post-holder">
<div class="register-message"></div>
<div class="post-content">
<form method="post" action="">
<div class="form-group">
<input type="text" id="name" class="form-control" placeholder="Full Name">
</div>
<div class="form-group">
<input type="text" id="username" class="form-control" placeholder="Username">
</div>
<div class="form-group">
<input type="password" id="password" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<input type="password" id="cpass" class="form-control" placeholder="Confirm Password">
</div>
<div class="form-group">
<input type="text" id="email" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<input type="text" id="dob" class="form-control" placeholder="Date of Birth">
</div>
<div class="form-group">
Sex
<input type="radio" id="sex" name="sex"> Male
<input type="radio" id="sex" name="sex"> Female
</div>
<div class="form-group">
<input type="checkbox" id="legal" name="legal"> I accept the Terms of Service and Privacy Policy.
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="<?php echo $mainf['set_recaptcha_sitekey']; ?>"></div>
</div>
<div class="form-group">
<input type="submit" id="submit" value="Register" class="btn btn-primary">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#login").click(function(){
var dataString = {
uname: $("#uname").val(),
pass: $("#pass").val(),
captcha: grecaptcha.getResponse()
};
$.ajax({
type: "POST",
//dataType : "json",
url: "processes/login.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#login").val("Please wait...");
$(".login-message").hide();
},
success: function(html){
$('.login-message').html(html).fadeIn();
if($('.login-message').find('#responseBox').hasClass('alert-success')){
setTimeout(function(){
window.location.replace("index.php");
}, 500);
}else{
$("#login").val("Log In");
}
}
});
return false;
});
$("#submit").click(function(){
var dataString = {
name: $("#name").val(),
uname: $("#username").val(),
pass: $("#password").val(),
cpass: $("#cpass").val(),
email: $("#email").val(),
dob: $("#dob").val(),
sex: $("input[name='sex']:checked").val(),
captcha: grecaptcha.getResponse()
};
$.ajax({
type: "POST",
//dataType : "json",
url: "processes/register.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").val("Please wait...");
$(".register-message").hide();
},
success: function(html){
$('.register-message').html(html).fadeIn();
$("#submit").val("Register");
}
});
return false;
});
});
</script>
I got the solution. In case someone comes looking for this it will help them.
In both HTML Forms replace
<div class="g-recaptcha" data-sitekey="YOUR_SITE_KEY"></div>
to
<div id="recaptcha1"></div> and <div id="recaptcha2"></div> respectively.
Then replace your script calling from
<script src="https://www.google.com/recaptcha/api.js></script>
to
<script src="https://www.google.com/recaptcha/api.js?onload=myCallBack&render=explicit" async defer></script>
And insert these code in your <script></script>. Note that this should be outside of $(document).ready(function() { and above your next form submission AJAX codes.
var recaptcha1;
var recaptcha2;
var myCallBack = function() {
recaptcha1 = grecaptcha.render('recaptcha1', {
'sitekey' : 'YOUR_SITE_KEY'
});
recaptcha2 = grecaptcha.render('recaptcha2', {
'sitekey' : 'YOUR_SITE_KEY'
});
};
Next and last thing, change the captcha: grecaptcha.getResponse() in your form submission AJAX code to captcha: grecaptcha.getResponse(recaptcha1) and captcha: grecaptcha.getResponse(recaptcha2) respectively (for both AJAX codes of login and register forms in my case). For full form submission code please refer to the code in my question above. Just replace the captcha: part here as said.
Done! Now you can proceed to server side validation in your language (PHP or ASP whatever).

on success of jquery validation the page not redirect on specific location

In my coding I am doing jQuery validation which is going successful but when it come to redirect page its not redirecting on given url. when i checked this using firebug it shows every correct field and also the html(given url). i dont know how to redirect the page.
on success i just want to open my admin_login/login page and if validation failed it goes on admin_login/index page.
<?php include('assets/header.php'); ?>
<div class="container">
<h1>Welcome to Admin Login</h1>
<?if($this->session->flashdata('flashError')):?>
<p class='flashMsg flashError'>
<?= $this->session->flashdata('flashError') ?> </p>
<?endif?>
<!-- new line inserted -->
<form method="post" name="myForm" accept-charset="utf-8" class="login" id="form" >
<div class="form-group">
<div class="col-xs-4">
<!--<label for="admin">Admin</label>
<input type="text" name="admin" class="form-control" id="admin" value="" placeholder="admin name" />-->
Admin Name: <input type="text" name="admin" id="admin" class="form-control" value="<?php echo set_value('admin'); ?>" placeholder="admin name" >
<?php echo form_error("admin"); ?>
<p id='p1'></p>
<br>
<!-- <label for="password">password</label>
<input type="text" name="password" class="form-control" id="password" value="" placeholder="password" required/>
-->
Admin Password: <input type="password" name="password" id="password" class="form-control" value="" placeholder="password" >
<?php echo form_error("password"); ?>
<p id='p2'></p>
<br>
<br>
<input type="button" name="submit" value="submit" id="submit" class="btn btn-primary" >
</div>
</div>
<div class="error"></div>
</form>
</div>
<script>
$(document).ready(function () {
$("#submit").click(function () {
var admin = $("#admin").val();
var password = $("#password").val();
$("#returnmessage").empty(); // To empty previous error/success message.
// Checking for blank fields.
if (admin == '')
{
$('div.error').html("Please Fill Admin Required Fields");
} else if (password == '')
{
$('div.error').html("Please Fill Password Required Fields");
} else
{//alert('hello world');
// Returns successful data submission message when the entered information is stored in database.
$.ajax({
type: "POST",
url: "<?php base_url() ?>index.php/admin_login/login",
data: {"admin": admin, "password": password},
dataType: "json"
}).done(function (data) {
if (data.error != "")
{
//alert('hello if');
$('div.error').html(data.error);
} else
{
// alert('hello else');
window.location.href="admin_view";
}
});
}
});
});
</script>
<?php include('assets/footer.php'); ?>
try this
here full path like this
window.location.assign("http://localhost/ss.php");
or
window.location.assign("<?php base_url() ?>index.php/admin_login/login");
You will get the response in success function.
$.ajax({
type: "POST",
url: "<?php base_url() ?>index.php/admin_login/login",
data: {"admin": admin, "password": password},
dataType: "json"
success : function (data) {
// alert('hello else');
window.location.href="<?php base_url() ?>index.php/admin_login/login";
},
error: function() {
$('div.error').html("An error occurred");
}
});
try using full URL
window.location.href="<?php base_url() ?>index.php/admin_login/login";

Cannot submit a form in jquery

I am using jquery smarty, php. I am validating a form using jquery but the submit button is not working.
In checkemail.php I am echoing no of rows;
$(document).ready(function() { //newly added
$("#formpge").submit(function(event) {
event.preventDefault();
var emailVal = $('#useremail').val();
alert(emailVal);
// assuming this is a input text field
$.post("checkemail.php", {
"useremail": emailVal
}, function(data) {
alert(data);
if (data == 0) {
alert("has to be added");
$("#formpge")[0].submit();
} else
$("#useremail").focus();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="formpge" name="frmadduser" method="post">
<div class="input1">
<input type="text" placeholder="Your Full Name" id="username" name="username">
</div>
<div class="input2">
<input type="text" placeholder="Your Email Address" id="useremail" name="useremail">
<p color="blue" id="emailexist"></p>
</div>
<div class="input1">
<input type="hidden" value="Y" name="active">
</div>
<div class="clear"></div>
<div class="iwant_text2">
<input type="submit" id="formsubmit" name="formsubmit" value="I Want One!">
</div>
</form>
try this code its working: -
<form id="formpge" name="frmadduser" method="post">
<div class="input1">
<input type="text" placeholder="Your Full Name" id="username" name="username">
</div>
<div class="input2">
<input type="text" placeholder="Your Email Address" id="useremail" name="useremail">
<p color="blue" id="emailexist"></p>
</div>
<div class="input1">
<input type="hidden" value="Y" name="active">
</div>
<div class="clear"></div>
<div class="iwant_text2">
<input type="submit" id="formsubmit" name="formsubmit" value="I Want One!" >
</div>
</form>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function(){ //newly added
$("#formpge").submit(function(event) {
event.preventDefault();
var emailVal = $('#useremail').val();
alert(emailVal);
// assuming this is a input text field
$.post("checkemail.php", {"useremail" : emailVal}, function(data) {
alert(data);
if(data == 0){
alert("has to be added");
$("#formpge")[0].submit();
}
else
$("#useremail").focus();
});
});
});
</script>
try fiddle here
First of all thanks to mplungjan, Gaurav Srivastava andStarscream1984. The problem is, in checkemail.php I checked isset($_REQUEST['formsubmit'], but this is not set only the text fields are set. I dont know why type submit is not set.
Again, Thanks.

How to make popup login and register from index.php to work and to parse data in mysql

I have:
Index.php, login.php, register.php
In index.php I have modal popup and I want to user can login and register from popup.
I try with ajax but not working.
Here is my code:
ajax.php:
function validLogin(){
var email=$('.email').val();
var password=$('.password').val();
$.ajax({
type: "POST",
url: "sign-in.inc",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true'){
alert ("Correct");
}
else{
alert ("Wrong");
}
}
});
}
and here is popup form :
<div id="login">
<form class="form login-form" name="login-popup" >
<a class="btn-facebook" href="#"><span><i class="fa fa-facebook"></i>
</span><span>Login with Facebook</span></a>
<a class="btn-google" href="#"><span><i class="fa fa-google-plus"></i>
</span>
<span>Login with Google</span></a>
<p class="fieldset">
<label class="image-replace email icon-log" for="signin-email">E-mail</label>
<input class="full-width has-padding has-border email" id="signin-email" name="email-login" type="email" placeholder="E-mail" name="email" required>
<span class="error_box"></span>
</p>
<p class="fieldset">
<label class="image-replace password" for="signin-password">Password</label>
<input class="full-width has-padding has-border password" id="signin-password" type="password" placeholder="Password"
name="password" required>
Show
<span class="error-message"></span>
</p>
<p class="fieldset">
<input type="checkbox" id="remember-me" checked>
<label for="remember-me">Remember me</label>
</p>
<p class="fieldset">
<input class="full-width orange" id="login-submit" type="submit" name="submit" onclick="validLogin()" value="Login">
</p>
</form>
<p class="form-bottom-message">Forgot your password?</p>
<!-- Close -->
</div>
First, I would advise moving your JQuery to using IDs for selectors and not Classes. Second, your url doesn't look right. Unless you have .inc being handled or mapped on your server, this will not be able to process the request. Take a look:
function validLogin(){
var email = $('#signin-email').val();
var password = $('#signin-password').val();
$.ajax({
type: "POST",
url: "sign-in.php",
data: "name="+email+"&pwd="+password,
success: function(html){
if(html=='true'){
alert ("Correct");
} else {
alert ("Wrong");
}
}
});
}

Ajax call won't pass - form always submitted by php

I've a form which is submitting with php uri_request by default.
Now i was trying to add an ajax call to submit the form, but it's still submitting with php
The ajax call for submitting the form is:
$(document).ready(function() {
$("#contactform").submit(function(e) {
e.preventDefault();
});
$.ajax({
cache: false,
type: 'POST',
data: ("#contactform").serialize(),
url: 'formfiles/submit.php',
// for ajax the submit.php is on a
success: function() {
// separate page
$('#contactform').fadeOut(200).submit();
$('#success').delay(200).fadeIn(200);
}
});
return false;
});
and the html form attributes are:
<form action="#n" class="active" method="post" name="contactform" id="contactform">
Also the
e.preventDefault
at the beginning of the ajax call won't work, but without the ajax it work (only the prevent default!)
What is wrong with the code? Why it doesn't work?
Thanks in advance for any help
EDIT here is the html {in an include file ( the hole site is a php dynamic structure)}
<form action="#n" class="active" method="post" name="contactform" id="contactform">
<div class="column">
<div class="obb" style="<?php echo $color[11];?>">
All fields are mandatory
</div>
<div >
<label style="<?php echo $color[0]; ?>"> Name:</label>
<input class="con_campo required" name="name" value="" id="name" type="text" />
</div>
<div >
<label style=""><?php echo $color[8]; ?> </label>
</div>
<div class="fieldcontent prod" id="pr">
<label style=""> <?php echo $color[2]; ?></label>
<select name="prod" value="" id="products" class="selectx required">
<option value=""> -- Select -- </option>
<option value="1"> ITA</option>
<option value="2">DE</option>
<option value="3"> FR</option>
<option value="4">EN</option>
</select>
</div>
<div class="fieldcontent prod" id="in">
<label style="<?php echo $color[4]; ?>"> Address:</label>
<input name="address" value="" id="address" class="required" type="text" />
</div>
<div class="fieldcontent prod" id="ci">
<label style="<?php echo $color[6]; ?>"> City:</label>
<input name="city" value="" id="city" class="con_campo required" type="text" />
</div>
<div class="fieldcontent info help" id="me" >
<label style="<?php echo $color[10]; ?>">Message:</label>
<textarea id="message" name="message" value="" class="cs_comment required" ></textarea>
</div>
<div id="code" style="margin-bottom:25px;">
<label style="<?php echo $color[11]; ?>; width:340px;"></label>
<input type="text" name="code" class="chapta" size="10" maxlength="7" id="code"/>
</div>
</div>
<div class="column" >
<div class="obb"> </div>
<div class="fieldcontent prod" id="co">
<label style="<?php echo $color[1]; ?>">Surname:</label>
<input name="surname" value="" id="surname" class=" required" type="text"/>
</div>
<div >
<label style="<?php echo $color[9]; ?>">Email: </label>
<input name="email" value="" id="email" class=" required email" type="text" />
</div>
<div class="fieldcontent help prod" id="do">
<label style="<?php echo $color[3]; ?>">Domain:</label>
<span style="font-size:20px; margin-left:30px;"> http://</span>
<input name="domain" id="domain" class=" required" type="text" value="" />
</div>
<div class="fieldcontent prod" id="re">
<label style="<?php echo $color[5]; ?>">Region:</label>
<input name="region" value="" id="region" class=" required" type="text" />
</div>
<div class="fieldcontent prod" id="pa">
<label style="<?php echo $color[7]; ?>" >State:</label>
<input name="state" value="" id="state" class="con_campo required" type="text" />
</div>
</div>
<div>
<div class="bottom">
<input type="submit" id="submitButton" name="submit" value="submit" />
<br /><br /><br />
</div>
</form>
</div></div>
<script>
$(document).ready(function() {
$("#contactform").submit(function(e){
$.ajax({
cache: false,
type: 'POST',
data: $("#contactform").serialize(),
url : 'formfiles/submit.php', // for ajax the submit.php is on a
success: function() { // separate page
$('#contactform').fadeOut(200).submit();
$('#success').delay(200).fadeIn(200);
}
});
});
});
You can restructure your code to fix the problem as below. You don't need return false; since e.preventDefault(); is gonna take care of it.
$(document).ready(function () {
$("#contactform").submit(function (e) {
e.preventDefault();
$.ajax({
cache: false,
type: 'POST',
data: $("#contactform").serialize(), //note that $ mark is added
url: 'formfiles/submit.php', // for ajax the submit.php is on a
success: function () { // separate page
$('#contactform').fadeOut(200).submit();
$('#success').delay(200).fadeIn(200);
}
});
});
});
You have an error in the ajax call in the line data: ("#contactform").serialize(). It should be data: $("#contactform").serialize()
Try this :
$(document).ready(function() {
$("#contactform").submit(function(e){
$.ajax({
cache: false,
type: 'POST',
data: $("#contactform").serialize(),
url : 'formfiles/submit.php', // for ajax the submit.php is on a
success: function() { // separate page
$('#contactform').fadeOut(200).submit();
$('#success').delay(200).fadeIn(200);
},
error: function(error_response){
console.log(error_response);
}
});
});
});
Update :
I see some issues with your code.
Is the required jQuery library loaded ? I don't see that in the html you had pasted. Hopefully you have included it in the header or so.
Add an e.preventDefault (); to prevent the form's default action since the input type is submit. If you don't put that the form will be submitted by default method.
I don't see the script tag closed. You should close the script tag else it will not work. Please see below the updated code:
<script type="text/javascript">
$(document).ready(function() {
$("#contactform").submit(function(e){
e.preventDefault();
$.ajax({
cache: false,
type: 'POST',
data: $("#contactform").serialize(),
url : 'formfiles/submit.php', // for ajax the submit.php is on a
success: function() { // separate page
$('#contactform').fadeOut(200).submit();
$('#success').delay(200).fadeIn(200);
}
});
});
});
</script>
New Update
Here your ajax call is returning no data. So the server will not know whether the call is success or not, it will always go to the success function. So you have to check whether the response is success or not. From the PHP page return some string like success to show whether the validation or form submission and its processing has been success or else return the error. Also on success callback you are submitting form again, so this will continue as a never ending loop.
Please make the below changes :
<script type="text/javascript">
$(document).ready(function() {
$("#contactform").submit(function(e){
e.preventDefault();
$.ajax({
cache: false,
type: 'POST',
data: $("#contactform").serialize(),
url : 'formfiles/submit.php', // for ajax the submit.php is on a
success: function(response) { // separate page
if (response == 'success') {
//write what you want to do on success
$('#success').delay(200).fadeIn(200);
} else {
//show error
}
}
});
});
});
</script>
Hope this helps

Categories