file not uploaded to the server with ajax - php

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

Related

How to successfully Insert into database using ajax in laravel?

Please have been trying to insert data into my database using ajax request in laravel. Am getting errors and i cant really find solution to it.Below is what I have done so far.
Header
<link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<meta name="_token" content="{{csrf_token()}}"/>
Blade file
<div class="content">
<form class="btn-submit" id="ajax" action="{{URL::to('insert-academic')}}">
<div class="form-group">
<label>Academic Year</label>
<input type="text" name="academic_year" class="form-control" placeholder="title" required="">
</div>
<div class="form-group">
<label>Description</label>
<input type="text" name="academic_description" class="form-control" placeholder="details" required="">
</div>
<div class="form-group">
<label>Semester</label>
<input type="text" name="academic_semester" class="form-control" placeholder="details" required="">
</div>
<div class="form-group">
<button class="btn btn-success">Submit</button>
</div>
</form>
</div>
<script type="text/javascript">
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('postinsert') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
</script>
Route
Route::post('insert-academic', 'AcademicYearController#addAcademic');
Controller File
public function addAcademic(Request $request)
{
$aca_year = new AcademicYear;
$aca_year -> academic_year = $request->input('academic_year');
$aca_year -> academic_description = $request->input('academic_description');
$aca_year -> academic_semester = $request->input('academic_semester');
$aca_year->save();
if ($aca_year) {
return response()->json([
'status' => 'success']);
} else {
return response()->json([
'status' => 'error']);
}
}
Am getting Error..Please how do I successfully add the data to the database
Blade file - remove form action attribute as it is of no use.
<div class="content">
<form class="btn-submit" id="ajax">
<div class="form-group">
<label>Academic Year</label>
<input type="text" name="academic_year" class="form-control" placeholder="title" required="">
</div>
<div class="form-group">
<label>Description</label>
<input type="text" name="academic_description" class="form-control" placeholder="details" required="">
</div>
<div class="form-group">
<label>Semester</label>
<input type="text" name="academic_semester" class="form-control" placeholder="details" required="">
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<div class="form-group">
<button class="btn btn-success">Submit</button>
</div>
</form>
</div>
<script type="text/javascript">
$("#ajax").on('submit', function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{route('postinsert')}}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert(data);
}
});
});
</script>
Route: add name for the route
Route::post('insert-academic', 'AcademicYearController#addAcademic')->name('postinsert);
Controller method:
public function addAcademic(Request $request){
$aca_year = new AcademicYear;
$aca_year->academic_year = $request->academic_year;
$aca_year->academic_description = $request->academic_description;
$aca_year->academic_semester = $request->academic_semester;
if ($aca_year->save()) {
return response()->json(['status'=> 'success']);
} else {
return response()->json(['status'=> 'error']);
}
}
Use submit not click. If you bind click, it will trigger when you click anywhere in form. You need to bind submit event.
$("#ajax").on('submit', function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('postinsert') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});

Jquery ajax function not working while submitting form

I'm trying to submit a form using ajax and php but for some reason my ajax is not working, when I try to hi the submit button it takes me to the page where my form will be process.
Form
<form id='formData' action="process/profile-settings" method="POST">
<div class="col-md-8">
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" value="<?php echo $user->userName(); ?>" disabled />
</div>
<div class="form-group">
<label>Description/Bio</label>
<input type="text" name="bio" class="form-control" value="" />
</div>
</div>
<button type="submit" class="btn d-block mx-auto" id="save" name="save">Save</button>
</form>
Ajax Code
$('document').ready(function(e) {
console.log('readyyyy');
$("#save").on('submit', function(e) {
e.preventDefault();
console.log('donwwwww');
var data = $("#formData").serialize();
$.ajax({
async: true,
url: 'process/profile-settings.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'post',
success: (response) => {
console.log('Doneeeee');
},
error: function(status, exception) {
alert('Exception:', exception);
}
});
});
e.preventDefault();
});
Note: I've removed my .php extension using .htaccess so didn't added .php in action attribute
I don't know why it is not working, I've tried all the possible methods
Appreciate your help

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.

Jquery-form-plugin implementation to current request call

I have a form with multiple file upload as well as others field along, normally I will request jquery ajax to process the data as below, and I can alert all input parameters and pass to server-side to perform certain task.
Since I have upload field in this form, I has acknowledged that is impossible to passes files data through $('#my_form').serialize(), I have some search here and know jquery form plugin can help with this issue, but I don't really get to know how it works, I hope somebody can enlighten me here with working example on how can I implement to above ajax method, and also how can I alert all input values is in post before send to sever-side to process, thanks for help!!!
Here is the current ajax request which is cannot see 'input type "file"' parameter:
$('#btn_submit').click(function(){
var parameters = $('#my_form').serialize();
var btn = $(this);
btn.button('loading')
alert(parameters);
$.ajax({
url: 'inc/callback/process.php',
type: 'POST',
data: parameters,
dataType: 'json',
success: function(response){
if(response.success == 'success'){
$('#successful').show().html('<b>saved!</b>');
}else{
$('[id$="_error"]').html('');
$.each(response.error, function(key, value){
if(value){
$('#' + key + '_error').html(value);
}
});
}
},
error: function(){
console.log(arguments);
}
}).always(function(){
btn.button('reset')
});
});
<form class="form-horizontal" role="form" method="post" id="my_form" enctype="multipart/form-data">
<input type="hidden" name="user_id" value="<?php echo $data->userid ?>">
<input type="hidden" name="list_id" value="<?php echo $listid ?>">
<div class="form-group">
<label for="photo">Photo</label>
<input type="file" name="files[]" class="multi" accept="gif|jpg" maxlength="3" />
</div>
<div class="form-group">
<label for="publish"></label>
<input type="checkbox" name="publish" <?php echo $checked ?>> Publish</div>
</div>
<div class="form-group">
<label for="email">Name</label>
<input type="text" id="name" name="name" value="<?php echo $list->name ?>"><span class="error" id="name_error"></span>
</div>
<hr />
<button class="btn btn-success" id="btn_submit" type="button" data-loading-text="Loading...">Save</button>
</form>
EDITED:
I've been tried the code provided by #Markus Fröhlich, but the form will submitted directly to inc/callback/process.php, seems like the ajaxForm doesn't trigger as well as alert never shown!
//this jq is refer as external js file at the bottom before </body>
$("#my_form").ajaxForm({
dataType: "json",
beforeSend: function() {
var btn = $(this);
btn.button('loading')
alert(parameters);
},
uploadProgress: function(event, position, total, percentComplete) {
console.log(percentComplete); // Show the completed percent
},
success: function(response) {
if(response.success == 'success'){
$('#successful').show().html('<b>Edited saved!</b>');
}else{
$('[id$="_error"]').html('');
// display invalid error msg
$.each(response.error, function(key, value){
if(value){
$('#' + key + '_error').html(value);
}
});
}
},
error: function(xhr, textStatus, errorThrown) {
console.log(errorThrown );
}
}).always(function(){
btn.button('reset')
});
<form class="form-horizontal" role="form" method="post" id="my_form" enctype="multipart/form-data" action="inc/callback/process.php">
<input type="hidden" name="user_id" value="<?php echo $data->userid ?>">
<input type="hidden" name="list_id" value="<?php echo $listid ?>">
<div class="form-group">
<label for="photo">Photo</label>
<input type="file" name="files[]" class="multi" accept="gif|jpg" maxlength="3" />
</div>
<div class="form-group">
<label for="publish"></label>
<input type="checkbox" name="publish" <?php echo $checked ?>> Publish</div>
</div>
<div class="form-group">
<label for="email">Name</label>
<input type="text" id="name" name="name" value="<?php echo $list->name ?>"><span class="error" id="name_error"></span>
</div>
<hr />
<button class="btn btn-success" id="btn_submit" type="submit" data-loading-text="Loading...">Save</button>
</form>
This code should works with ajaxForm! (Not tested!!!)
Don't forget the new form action, and the Button Type is now "submit".
$("#my_form").ajaxForm({
dataType: "json",
beforeSend: function() {
var btn = $(this);
btn.button('loading')
alert(parameters);
},
uploadProgress: function(event, position, total, percentComplete) {
console.log(percentComplete); // Show the completed percent
},
success: function(response) {
if(response.success == 'success'){
$('#successful').show().html('<b>saved!</b>');
}else{
$('[id$="_error"]').html('');
$.each(response.error, function(key, value){
if(value){
$('#' + key + '_error').html(value);
}
});
},
error: function(xhr, textStatus, errorThrown) {
console.log(errorThrown );
}
});
<form action="inc/callback/process.php" class="form-horizontal" role="form" method="post" id="my_form" enctype="multipart/form-data">
<input type="hidden" name="user_id" value="<?php echo $data->userid ?>">
<input type="hidden" name="list_id" value="<?php echo $listid ?>">
<div class="form-group">
<label for="photo">Photo</label>
<input type="file" name="files[]" class="multi" accept="gif|jpg" maxlength="3" />
</div>
<div class="form-group">
<label for="publish"></label>
<input type="checkbox" name="publish" <?php echo $checked ?>> Publish</div>
</div>
<div class="form-group">
<label for="email">Name</label>
<input type="text" id="name" name="name" value="<?php echo $list->name ?>"><span class="error" id="name_error"></span>
</div>
<hr />
<button class="btn btn-success" id="btn_submit" type="submit" data-loading-text="Loading...">Save</button>
</form>

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