Ajax call won't pass - form always submitted by php - 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

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";

In jquery form validation ajax not responding

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.

file not uploaded to the server with ajax

This is my form source:
<form id="createProject" name="createProject" class="form-light" method="post" enctype="multipart/form-data" target="upload_target">
<div class="col-md-10" id="sandbox-container1">
<label>Project duration</label>
<div class="input-daterange input-group" id="datepicker">
<input type="text" required class="input-md form-control" id="start" name="start" />
<span class="input-group-addon">to</span>
<input type="text" required class="input-md form-control" id="end" name="end" />
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label>Project attachment's</label>
<input type="file" class="form-control" id="projectFile" name="projectFile" placeholder="Select project attachment's">
</div>
</div>
<input type="hidden" id="ownerid" name="ownerid" value="<?php echo $userid; ?>">
<div class="col-md-10">
<div class="form-group">
<button class="btn btn-two pull-right btn-lg" form="createProject" type="submit">Submit</button>
</div>
</div>
</form>
File is not uploading to the server.
I use ajax function to submit.
$.ajax({
url:'ajaxcalls/createprojectfunction.php',
data:$(this).serialize(),
type:'POST',
beforeSubmit: function()
{
/* Before submit */
for ( instance in CKEDITOR.instances )
{
CKEDITOR.instances[instance].updateElement();
}
},
success:function(data){
console.log(data);
},
error:function(data){
}
});
Firebug console this error occur.
Notice: Undefined index: projectFile.
but all other input element are accessable in ajax URL php file.
You'll have to use a FormData object to upload a file via ajax,
$.ajax({
url:'ajaxcalls/createprojectfunction.php',
data: new FormData(this),
type:'POST',
processData: false,
contentType: false,
beforeSubmit: function()
{
/* Before submit */
for ( instance in CKEDITOR.instances )
{
CKEDITOR.instances[instance].updateElement();
}
},
success:function(data){
console.log(data);
},
error:function(data){
}
});

jquery ajax just isn't working

Ok, thats basically what i got. I also tried static values.
$('#submitForm').submit(function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
});
What i get as response is this:
Object {readyState: 0, responseText: "", status: 0, statusText = "error"}
The php script (just a simple echo) runs as normal after that ajax call. What am i doing wrong? My submit script doesn't look all that wrong to me and i'm not doing XSS. : - (
My HTML Form looks like this:
<form action="http://dev.xxxxxxx.de/users/register" method="post" accept-charset="utf-8" class="form-horizontal" id="submitForm"> <div class="control-group">
<label class="control-label" for="inputUsername">Nickname</label>
<div class="controls">
<input type="text" name="username" id="inputUsername" value="" placeholder="Nickname" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">E-Mail</label>
<div class="controls">
<input type="text" name="email" id="inputEmail" value="" placeholder="E-Mail" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Passwort</label>
<div class="controls">
<input type="password" name="password" id="inputPassword" value="" placeholder="Passwort" />
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn" value="Account erstellen" />
</div>
</div>
</form>
You need to tell the browser not to submit the form by default with:
e.preventDefault();
So:
$('#submitForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
});
Otherwise, your form will submit according to the "action" attribute, before your AJAX returns.

Categories