How to receive jquery ajax data in a php file - php

I am trying to create a form for submitting resume.
I need the candidate name, email , resume cover and the resume(file).
var candidateName = $('#candidateName').val();
var candidateEmail = $('#candidateEmail').val();
var candidateMessage = $('#candidateMessage').val();
var file_data = $('#candidateResume').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('name', candidateName);
form_data.append('id', candidateEmail);
form_data.append('msg', candidateMessage);
console.log(form_data);
$.ajax({
url: "cvForm.php",
type: "POST",
data: {candata: form_data},
success : function(data){
console.log(data);
},
contentType: false,
processData: false
});
nothing is being returned in my cvForm.php file when I
var_dump($_POST) or
var_dump($_FILES)
when I
var_dump($_POST['candata']) - it says undefined index
The HTML
<form id="cvSubmit" class="mui-form">
<div>
<span class="form-success-msg" id="cv-form-success-msg">
Thanks for reaching out to us. We will get back to you shortly.
</span>
</div>
<div class="row">
<div class="col-sm-6">
<div class="mui-textfield mui-textfield--float-label">
<input type="text" id="candidateName" class="mui--is-empty mui--is-untouched mui--is-pristine">
<label>Name<span class="red-text">*</span></label>
<span class="error" id="cv-name-error">Please enter your name</span>
</div>
<div class="mui-textfield mui-textfield--float-label">
<input type="email" id="candidateEmail" class="mui--is-empty mui--is-untouched mui--is-pristine">
<label>Email<span class="red-text">*</span></label>
<span class="error" id="cv-email-error">Oops!! Looks like its an incorrect email id. Try again</span>
</div>
<div class="row">
<div class="col-xs-12 file-attachment-wrapper">
<input class="file-addach" type="file" id="candidateResume">
<span>We accept .DOCX,.Doc,pdf,.Txt upto 2 MB.</span>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="mui-textfield mui-textfield--float-label">
<label>Message<span class="red-text">*</span></label><br><br>
<textarea id="candidateMessage" rows="5" class="mui--is-empty mui--is-untouched mui--is-pristine"></textarea>
<span class="error" id="cv-message-error">That's not very clear...could you rephrase</span>
</div>
<button type="button" class="mui-btn mui-btn--raised red-btn" onclick="cvSubmit()"> SEND </button>
</div>
</div>
</form>
Please help. I see this is a common question but none of the solution seems to work for me. Some code refreshes the page, which I don't want to happen.

Remove this line from your JS:
contentType: false,
That's telling jQuery to not set the content-type HTTP header. That header tells PHP how to parse the POSTed body.
Also, formdata can be sent directly:
data: form_data,
Then, in PHP, you should find for example $_POST['name'] available.

You need to pass form_data in its normal form, instead of a property of another JSON object:
$.ajax({
url: 'cvForm.php',
type: 'post',
data: form_data,
processData: false,
success : function(data){
console.log(data);
}
});
Now inside of your PHP script, you will have access to $_POST['name'], $_POST['id'] and $_POST['msg']. Similarly, $_FILES['file'] is now available too.

Try this. It might help you.
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<form id="cvSubmit" class="mui-form">
<div>
<span class="form-success-msg" id="cv-form-success-msg">
Thanks for reaching out to us. We will get back to you shortly.
</span>
</div>
<div class="row">
<div class="col-sm-6">
<div class="mui-textfield mui-textfield--float-label">
<input type="text" id="candidateName" class="mui--is-empty mui--is-untouched mui--is-pristine">
<label>Name<span class="red-text">*</span></label>
<span class="error" id="cv-name-error">Please enter your name</span>
</div>
<div class="mui-textfield mui-textfield--float-label">
<input type="email" id="candidateEmail" class="mui--is-empty mui--is-untouched mui--is-pristine">
<label>Email<span class="red-text">*</span></label>
<span class="error" id="cv-email-error">Oops!! Looks like its an incorrect email id. Try again</span>
</div>
<div class="row">
<div class="col-xs-12 file-attachment-wrapper">
<input class="file-addach" type="file" id="candidateResume">
<span>We accept .DOCX,.Doc,pdf,.Txt upto 2 MB.</span>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="mui-textfield mui-textfield--float-label">
<label>Message<span class="red-text">*</span></label><br><br>
<textarea id="candidateMessage" rows="5" class="mui--is-empty mui--is-untouched mui--is-pristine"></textarea>
<span class="error" id="cv-message-error">That's not very clear...could you rephrase</span>
</div>
<button type="submit" class="mui-btn mui-btn--raised red-btn"> SEND </button>
</div>
</div>
</form>
<script>
$(document).ready(function(){
$("#cvSubmit").submit(function(e) {
e.preventDefault();
var candidateName = $('#candidateName').val();
var candidateEmail = $('#candidateEmail').val();
var candidateMessage = $('#candidateMessage').val();
var file_data = $('#candidateResume').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('name', candidateName);
form_data.append('id', candidateEmail);
form_data.append('msg', candidateMessage);
console.log(form_data);
$.ajax({
url: "cvForm.php",
type: "POST",
data: form_data,
success : function(data){
console.log(data);
},
contentType: false,
processData: false
});
});
});
</script>
</body>
</html>
After this code, I was able to see the data in console
Changes the submit button to type 'submit' and handled the event handler for form submit and e.preventDefault() prevents from page refresh.
Hope it helps!

Related

How to serialize form in ajax and save data in database with laravel?

I have a form in which I user can insert multiple inputs fields and save to database using ajax
Here are the inputs,
I'm trying to send a serialized form to my database. My question is that when I serialize the form, use JQuery to attach it to a hidden input field, and then send the the form and some other information to the database, the rest of the information is reaching the database but I still have a blank in where the serialized form is. If anyone could point out where I went wrong and/or explain how this should be done I'd be very grateful! Thank you very much!
blade
<form method="post" id="form-job-store">
<input type="hidden" name="url" value="{{ route('job.store') }}">
#csrf
<div class="row">
<div class="col-md-6 mb-3">
<div class="col-md-6 mb-3">
<label for="history">history</label>
<input type="text" class="form-control" id="history" name="history">
</div>
<div class="col-md-6 mb-3">
<label for="post_title">post_title</label>
<input type="text" class="form-control" id="post_title" name="post_title">
</div>
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<button type="submit" class="btn btn-success" id="btn-job-submit"><i class="fas fa-plus fa-xs"></i> Save</button>
</div>
</div>
<form>
script
$(document).ready(function () {
$('#btn-job-submit').on('click', function (event) {
event.preventDefault();
var formData = new FormData($('#form-job-store')[0]);
let url = $('#form-job-store :input')[0].getAttribute('value');
$.ajax({
type: 'POST',
url,
data: $(formData).serialize(),
success: function (data) {
alert(data);
},
});
});
});
web.php
Route::resource('job', 'JobController');
JobController.php
public function store(Request $request)
{
$job = Job::create([
'user_id' => auth()->id(),
'post_title' => $request->post_title,
'history' => $request->history,
]);
return response()->json($job);
}
You have to use like this
$(document).ready(function(){
$('#btn-job-submit').on('submit', function(event){
event.preventDefault();
$.ajax({
url:'{{route('job.store')}}',
method:"POST",
data:new FormData(this),
dataType:'JSON',
contentType: false,
cache: false,
processData: false,
success:function(data){
}
})
})
})

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

PHP ajax post data empty

I am posting form data from create.php as below using $.ajax.
$(document).ready(function () {
var request;
$("#create-pto").submit(function(e) {
// Abort any pending request
if (request) {
request.abort();
}
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: 'index.php',
type: 'POST',
contentType : 'application/json',
data: serializedData
}).done(function (response, textStatus, jqXHR) {
// Log a message to the console
console.log("Hooray, it worked!");
});
e.preventDefault();
});
});
I can see the posted data and i can log post success.
But in index.php could not retrieve posted data.
This is what i am trying in index.php
var_dump($_POST);
Form :
<form class="form-horizontal" id="create-pto" >
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control- label">App ID</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="app-id" id="app-id" placeholder="App ID">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">App Name</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="app-name" id="app-name"
placeholder="App Name">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Instance Name</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="inputPassword3" name="ins-name"
placeholder="Instance Name">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="create" class="btn btn-success">Create PTO</button>
</div>
</div>
</form>
Pls help.
Try changing the contentType on your JavaScript code:
contentType : 'application/x-www-form-urlencoded',
And if you want to keep the contentType to json, try this way on your PHP file:
echo file_get_contents('php://input');
If you use .serialize() you need to change contentType to 'application/x-www-form-urlencoded'.
If you want to keep contentType: 'application/json' you have to use JSON.stringify instead.
Also note that JSON strings in POST requests are retreived using file_get_contents('php://input'); not $_POST
Change your
contentType : 'application/json'
to
dataType: "JSON"
It will start work.. I tested code on my system.
try type:GET instead of type:POST,also call var_dump($_GET) in index.php

Ajax POST form to PHP

Trying to post my form using Ajax. Using Apache Cordova but can't seem to send it to my php form. Any ideas of how to get my form to work would be appreciated.
<script type="text/javascript">
$('#userform').submit(function(){
var postData = $(this).serialize();
$.ajax({
type: 'POST',
data: postData,
url: 'http://myurl/dbInsertUserslocal.php',
success: function(data){
console.log(data);
alert('User successfully added');
},
error: function(){
console.log(data);
alert('There was an error adding New User');
}
});
return false;
});
</script>
and my form looks like:
<form id="userform" method="Post">
<div class="row">
<div class="large-4 columns">
<label>First/Last Name
<input type="text" name="firstlast" />
</label>
</div>
</div>
<div class="row">
<div class="large-2 columns">
<label>Title
<select name="title" >
<option value=""></option>
<option value="Inspector">Inspector</option>
<option value="Tech">Technician</option>
<option value="Supervisor">Supervisor</option>
</select>
</label>
</div>
</div>
<div class="row" >
<div class="large-12 columns">
<hr class="intro-divider">
<input type="file" capture="camera" accept="image/*"
id="snap" name="photo">
</div>
</div>
<hr class="intro-divider">
</div>
</div>
<div class="row">
<div class="large-2 columns">
<button class="tiny" type="submit" value="Submit"
id="submit" data-role="button" data-ajax="false">Add User</button>
</div>
</div>
</form>
If you include the file in form, you must use multipart/form-data.
<form id="userform" method="Post" enctype="multipart/form-data">
serialize method can't see the file data.
By using the FormData object instead of serialize method, the javascripts code becomes
$(function(){
$('#userform').submit(function(){
var fd = new FormData( $(this)[0] );
$.ajax({
type: 'POST',
processData: false,
contentType: false,
data: fd,
dataType: "text",
url: 'http://myurl/dbInsertUserslocal.php',
success: function(data){
alert( data );
alert('User successfully added');
},
error: function(){
alert('There was an error adding New User');
}
});
return false;
});
});
However, some devices does not equip the FormData object.
Check
http://caniuse.com/#search=FormData

Categories