Jquery ajax function not working while submitting form - php

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

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

Laravel 5.8 file upload using PUT method with ajax

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.

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.

How to make jquery script work for new generated form

I have one script which display the form on click response
$(".table th .glyphicon-edit").one('click', function(){
var $this = $(this);
var sectionName = $(this).attr('data-sectioname');
var courseId = $(this).attr('data-courseid');
var sectionId = $(this).attr('data-sectionid');
$.get('/edit_section', { section: sectionName, id: courseId, sectionid: sectionId}, function(response) {
$this.closest('thead tr').after(response);
});
});
"edit_section" page
<form method="POST" action="http://localhost:8000/managecourse/162" accept-charset="UTF-8" id="edit" class="form-horizontal">
<input name="_method" value="PUT" type="hidden">
<input name="_token" value="duTA8TbvmYeJWUA21VTGqZYisQZu1ouuhvbXCouv" type="hidden">
<input name="sectionid" value="1" type="hidden">
<input name="courseid" value="162" type="hidden">
<div class="form-group">
<label for="section_name" class="col-md-4 control-label text-right">Name sectiton</label>
<div class="col-md-6">
<input class="form-control" name="section_name" value="Name_section" id="section_name" type="text">
</div>
</div>
<div class="form-group text-center">
<input name="edit" class="btn btn-primary" value="Save" type="submit">
</div>
</form>
And then I have script to submit this form but it doesn't work
$('#edit').submit(function(e) {
e.preventDefault();
var sectionName = $('input#section_name').val();
var sectionId = $('input[name=sectionid]').val();
$.ajax({
type: 'POST',
cache: false,
dataType: 'JSON',
url: '/managecourse/update',
data: $('#edit').serialize(),
success:function(data){
console.log(data);
},
});
});
It just display new page with json data but would like to display this data at the same page without reload.
Delegate your submit method. it will work on dynamically added elements.
$(document).on('submit','#edit',function(){
// code
});

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

Categories