jquery ajax just isn't working - php

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.

Related

jQuery Ajax passing input values from one modal to another

I have a modal for entering user information. A user should be linked to a building. After user information has been entered and submit button has been clicked, I am preventing the default action and am overlaying/showing a building modal over the user modal.
Code for doing so follows.
(function($) {
$('#modalAddUser').modal('show');
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: './modals/modalConnectBuilding.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function() {
console.log(name_user);
console.log(address_user);
console.log(city_user);
}
});
$('#modalConnectBuilding').modal('show');
});
})(window.jQuery);
console.log() logs the input information correctly, however in 'modalConnectBuilding.php' the following does not work:
<?php
echo $_POST['name_user'];
echo $_POST['address_user'];
echo $_POST['city_user'];
?>
Producing the following errors:
Undefined index: name_user in
C:\laragon\www\modals\modalConnectBuilding.php
Undefined index: address_user in
C:\laragon\www\modals\modalConnectBuilding.php
Undefined index: city_user in
C:\laragon\www\modals\modalConnectBuilding.php
My intent is to do a classic 'form action="./php/processConnectBuilding.php" method="post"' but would need access to the three undefined variables as seen above. Adding users and buildings works in isolation but not when connected in this way. Any help would be greatly appreciated and if you need any more info, please ask. Thank you!
Code for the form (within the modal) I'm submitting follows (please note, default action is being suppressed by preventDefault() so action attribute is never "called", also the form for connecting a building is basically the same, but the action attribute is not suppressed):
<form role="form" id="formAddUser" action="./php/processAddUser.php" method="post">
<div class="form-group form-group-default required">
<label>Name</label>
<input type="text" name="name" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>Address</label>
<input type="text" name="address" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>City</label>
<input type="text" name="city" class="form-control" required>
</div>
<div style="margin-top: 25px">
<button type="submit" class="btn btn-primary btn-lg btn-block"><i class="fa fa-plus-circle"></i> Add</button>
</div>
</form>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
</head>
<body>
<form role="form" id="formAddUser" action="" method="post">
<div class="form-group form-group-default required">
<label>Name</label>
<input type="text" id="name" name="name" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>Address</label>
<input type="text" name="address" class="form-control" required>
</div>
<div class="form-group form-group-default required">
<label>City</label>
<input type="text" name="city" class="form-control" required>
</div>
<div style="margin-top: 25px">
<button type="submit" class="btn btn-primary btn-lg btn-block"><i class="fa fa-plus-circle"></i> Add</button>
</div>
</form>
</body>
</html>
<script>
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: 'tariffdetaildata.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function(data) {
alert(data)
}
});
});
</script>
tariffdetaildata.php
<?php
echo $_POST['name_user'];
echo $_POST['address_user'];
echo $_POST['city_user'];
Try this way I think you need to open the modal popup once you get the response back from the ajax.
(function($) {
$('#modalAddUser').modal('show');
$('#formAddUser').on('submit', function(e) {
e.preventDefault();
let name_user = $('input[name="name"]').val();
let address_user = $('input[name="address"]').val();
let city_user = $('input[name="city"]').val();
$.ajax({
url: './modals/modalConnectBuilding.php',
method: 'post',
data: {
"name_user": name_user,
"address_user": address_user,
"city_user": city_user
},
success: function() {
console.log(name_user);
console.log(address_user);
console.log(city_user);
$('#modalConnectBuilding').modal('show');
$("#modalConnectBuilding .modal-body #name_user").val( name_user);
$("#modalConnectBuilding .modal-body #address_user").val( address_user);
$("#modalConnectBuilding .modal-body #city_user").val( city_user);
}
});
});
})(window.jQuery);

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).

laravel ajax post serialize not working

<form id="sendmemessage">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<div class="form-group">
<h2 class="open-f bbold green-text contact-t">SEND ME A MESSAGE!</h2>
</div>
<div class="form-group">
<input type="text" name="name" class="form-control input-sm no-radius" aria-describedby="emailHelp" placeholder="Name">
</div>
<div class="form-group">
<input type="text" name="email" class="form-control input-sm no-radius" placeholder="Email">
</div>
<div class="form-group">
<input type="text" name="subject" class="form-control input-sm no-radius" placeholder="Subject">
</div>
<div class="form-group">
<textarea class="form-control input-sm no-radius" name="message" rows="5" placeholder="Message"></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-custom pull-right btn-w">Send Message</button>
</div>
<br>
</form>
I am trying to subit the values of the form,i know this is just basic but i dont know why is not working.
below is my ajax,
$("#sendmemessage").submit(function(stay){
$.ajax({
type: 'POST',
url: "{{ url('/') }}/message_me",
data: $(this).serialize(),
success: function (data) {
alert();
},
});
stay.preventDefault();
});
my route
Route::post('message_me','home_controller#message_me');
my controller
class home_controller extends Controller{
public function message_me(){
echo "its here!";
}
}
here are my form details code
$(this).serialize() was inside the ajax object and it refers to ajax not the form.
$("#sendmemessage").submit(function(stay){
var formdata = $(this).serialize(); // here $(this) refere to the form its submitting
$.ajax({
type: 'POST',
url: "{{ url('/') }}/message_me",
data: formdata, // here $(this) refers to the ajax object not form
success: function (data) {
alert();
},
});
stay.preventDefault();
});
Start with replacing
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
with the helper function
{!! csrf_field() !!}
I structure my ajax calls like the following:
$("#sendmemessage").on('submit', function(e) {
e.preventDefault();
var data = $("#sendmessage").serialize();
$.ajax({
type: "post",
url: "/message_me",
data: data,
dataType: "json",
success: function(data) {
console.log('success');
},
error: function(error) {
console.log('error');
}
});
});
Can you access the "message_me" route via the browser? A 500 internal server error should give you clear insight why the request fails.

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){
}
});

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