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
Related
I need help!
i need to know how i can detect button name for upload.php file so i can put if(isset($_post['aa'))
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
url: "upload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function()
{
}
});
}));
});
</script>
The Form
<form id="uploadForm" action="upload.php" method="post">
<div class="row">
<div class="col-md-12 mb-1">
<div id="targetLayer">No Image</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input name="text" type="text" class="inputFile form-control" />
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input name="userImage" type="file" class="inputFile form-control" />
</div>
</div>
<div class="col-md-12">
<div class="form-group text-center">
<input type="submit" value="Save" name="aa" class="btnSubmit btn btn-success" />
</div>
</div>
</div>
</form>
Submit buttons are not generally/automatically sent in ajax requests.
They aren't added to FormData or .serialize().
In your code, add this field manually.
<script type="text/javascript">
$(document).ready(function (e) {
$("#uploadForm").on('submit',(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
var formData = new FormData(this);
formData.append('aa', 'Save');
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function()
{
}
});
}));
});
</script>
In this form you mentioned that the name of the button is aa
so it will become
if(isset($_POST['aa']) && $_POST['aa'] == 'Save') ...
Here is the screenshot of what it looks like when request is posted.
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){
}
})
})
})
I'm trying to update a file using a PUT method with ajax. For whatever reason I can't send a request in my controller. I created a custom validator to check whether a file is missing or a certain input request is missing. It keeps on returning 422 file is missing and name is missing. What do I miss? Here's my code below.
<script>
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#news_id').on('submit', function(e) {
e.preventDefault();
var data = new FormData();
var newsletter_name = $('#newsletter_name').val();
var newsletter_file = $('#newsletter_file')[0].files[0];
data.append('newsletter_name', newsletter_name);
data.append('newsletter_file', newsletter_file);
var id = $('#hidden_id').val();
console.log(newsletter_file);
$.ajax({
url: '/admin/newsletter/' + id,
type: 'PUT',
data: data,
contentType: false,
processData: false,
beforeSend: function(data) {
},
success: function(data) {
console.log('success');
},
error: function(data) {
console.log(data)
},
});
});
});
</script>
Here's my html code
<div class="container mt-5">
<div class="col-md-6">
<form action="" method="" enctype="multipart/form-data" id="news_id">
#method('PUT')
<div class="form-group">
<label for="newsletter_name">Name</label>
<input type="text" value="{{$newsletter->newsletter_name}}" name="newsletter_name" id="newsletter_name" class="form-control" placeholder="" aria-describedby="helpId">
<input type="hidden" name="hidden_id" id="hidden_id" value="{{$newsletter->newsletter_id}}">
<input type="hidden" name="_method" value="PUT">
</div>
<div class="input-group mb-3">
<div class="custom-file">
<input name="newsletter_file" type="file" class="custom-file-input" id="newsletter_file" aria-describedby="inputGroupFileAddon03">
<label class="custom-file-label" for="newsletter_file">Choose file</label>
</div>
</div>
<div>
<button class="btn btn-primary btn-block" type="submit">UPDATE</button>
</div>
</form>
</div>
</div>
Add data.append('_method', 'PUT'); then change your request type to type: 'POST'
Because some browser can't send a PUT request, so Laravel can do receive a PUT request by receiving _method data.
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!
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){
}
});