laravel ajax post serialize not working - php

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

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

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.

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

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

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