comment system using ajax with laravel without reloaded page - php

I want to add a comment system on my website using AJAX with Laravel to load new comments without refreshing whole page.
I always have this error :
Ajax Post 500 (Internal Server Error)
below is my code:
view page :
{!! Form::open(array('action' => array('PersonsController#newComment', $person->id))) !!}
<div class="form-group">
{!! Form::label('name', 'Nom ') !!}
{!! Form::text('name', null, ['class' =>'form-control', 'style'=>'border-radius: 0']) !!}
</div>
<div class="form-group">
{!! Form::label('mail', 'E-mail ') !!}
{!! Form::text('mail', null, ['class' =>'form-control', 'style'=>'border-radius: 0']) !!}
</div>
<div class="form-group">
{!! Form::label('comment', 'Contenu ') !!}
{!! Form::textarea('comment', null, ['class' =>'form-control', 'style'=>'border-radius: 0']) !!}
</div>
<div class="form-group">
{!! Form::submit('Publier', array('class'=>'send-btn')) !!}
</div>
{!! Form::close() !!}
route page :
Route::get('{id}/apropos','PersonsController#show');
Route::post('{id}/apropos','PersonsController#newComment');
Controller page :
public function newComment($id) {
if ($request::ajax()) {
$name = Input::get('name');
$mail = Input::get('mail');
$comment = Input::get('comment');
$Comments = new \App\Comment;
$Comments->Persons_id = $id;
$Comments->date = \Carbon\Carbon::now();
$Comments->name=$name;
$Comments->mail=$mail;
$Comments->comment=$comment;
$Comments->save();
$reponse =array(
'status' => 'success',
'msg' => 'Setting created successfully',
);
return \Response::json($response);
} else {
return 'no';
}
}
Ajax page :
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function() {
$('.send-btn').click(function (e) {
e.preventDefault();
var name = $('#name').val();
var mail = $('#mail').val();
var comment = $('#comment').val();
$.ajax({
type: "POST",
url: '{{url("1/apropos")}}',
dataType: 'JSON',
data: {name: name, mail: mail, comment: comment},
success: function( data ) {
$("body").append("<div>"+data+"</div>");
}
});
});
});

I suppose that your ajax page is in the same page than the view (because you are using .send-btn).
It´s easier to use $.post() because you don´t need to configure so many parameters. https://api.jquery.com/jquery.post/
Do you have more information about the error: Ajax Post 500 (Internal Server Error). Don´t you have any message? Use error function on $.ajax:
error callback option is invoked, if the request fails. It receives
the jqXHR, a string indicating the error type, and an exception object
if applicable. Some built-in errors will provide a string as the
exception object: "abort", "timeout", "No Transport".
so you can add at your AJAX request something like:
error: function (xhr, textStatus, thrownError) {
console.log(xhr.status);
console.log(xhr.statusText);
console.log(textStatus);
console.log(thrownError);
}

Related

Can't read responseJSON value in ajax request

This is the view :
{{ Form::open([
'url' => '/contacts/create',
'files' => true
])}}
<div class="row">
<div class="collapse" id="collapseExample">
<div class="col-md-9">
{{ Form::label('group', 'group name')}}
{{ Form::text('group', null, [
'placeholder' => 'Enter group name here',
'class' => 'form-control'
])}}
</div>
<div class="col-md-3">
<button id="add-new-btn" class="btn btn-success"><i class="pe-7s-add-user"></i> Add</button>
</div>
</div>
</div>
{{ Form::close() }}
in my that view i have this script
$("#add-new-btn").click(function(e) {
e.preventDefault();
e.stopImmediatePropagation();
var newGroup = $('#group');
$.ajax({
url: "/groups/autocomplete",
method: "post",
data: {
name: $("#group").val(),
_token: $("input[name=_token]").val()
},
success: function(response) {
console.log(response);
},
error: function(xhr) {
var errors = xhr.responseJSON;
var error = errors.name[0];
if(error) {
newGroup.addClass('has-error');
var inputGroup = newGroup.closest('.col-md-9');
inputGroup.next('text-danger').remove();
inputGroup
.find('input')
.after('<p class="text-danger">' + error + '</p>');
}
}
});
});
and in store method of GroupsController i have a simple Validator that may returns these 2 values:
1.The name field is required
2.The name has already been taken
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|unique:groups'
]);
}
Now the problem is this :
Every time i try to submit the form, the browser returns this error "errors.name is undefined" in console.
where is the problem?
i had a mistake for accessing property of object, jsonData.errors
var data = xhr.responseText;
var jsonData = JSON.parse(data);
var msg = jsonData.errors.name[0];
console.log(msg);
or
var jsonData = xhr.responseJSON;
var msg = jsonData.errors.name[0];
console.log(msg);

laravel: image not being submitted with form

I have this form in a page:
<div class="card-block">
{!! Form::open(array( 'autocomplete' => 'off', 'id' => 'AddModel', 'url' => 'model/useradd', 'files' => true)) !!}
<div class="form-group">
<label for="picture">Picture</label>
#if( (new Jenssegers\Agent\Agent)->isMobile() )
{!! Form::file('image', ['id' => 'modelpic', 'accept' => 'image/*', 'capture' => 'camera']) !!}
#else
{!! Form::file('image', ['id' => 'modelpic']) !!}
#endif
<br/>
</div>
<div id="imagePreview" style="display: none;"></div> /** here I show preview of the image through JS */
<div class="form-group">
{!! Form::submit('Submit', array('id' => 'AddBtn', 'class' => 'btn btn-default' )) !!}
{!! Form::close() !!}
</div>
in my controller:
public function preview(Request $request)
{
dd($request->file('image'));
}
result of dumping = NULL
I don't understand what's the catch here. I have an identical form in another page that is working normally.
by validating request I get the error "image is required"
$this->validate($request, [
'image' => 'required|mimes:jpeg,jpg,png,gif|image|image_size:>=640'
]);
new info:
There must be a problem with the javascript because removing it the controller works normally:
this is the JS
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", "#AddModel", function (e) {
var form = $(this);
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
console.log(data);
},
error: function (textStatus) {
{
var json = JSON.parse(textStatus.responseText);
console.log (json);
}
}
});
e.preventDefault();
});
});
});
solved, thanks #sagar
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", "#AddModel", function (e) {
var form = $(this);
var postData = new FormData($("#AddModel")[0]);
$.ajax({
type:'POST',
url:form.prop('action'),
processData: false,
contentType: false,
data : postData,
success:function(data){
console.log(data);
},
error: function (textStatus) {
{
var json = JSON.parse(textStatus.responseText);
console.log (json);
}
}
});
e.preventDefault();
});
});
});
To upload image using ajax:
Do it like:
You can upload the file using ajax like this.
In your form tag use attribute enctype and form html will be like below:
<form enctype="multipart/form-data" id="modal_form_id" method="POST" >
<input type="file" name="documents">
</form>
Js code:
var postData = new FormData($("#modal_form_id")[0]);
$.ajax({
type:'POST',
url:'your-post-url',
processData: false,
contentType: false,
data : postData,
success:function(data){
console.log("File Uploaded");
}
});
On your controller side you can do in the function like below to upload image.
if(Input::hasFile('documents')) {
$path = "directory where you wish to upload file";
$file_name= Input::file('documents');
$original_file_name = $file_name->getClientOriginalName();
$extension = $file_name->getClientOriginalExtension();
$fileWithoutExt = str_replace(".","",basename($original_file_name, $extension));
$updated_fileName = $fileWithoutExt."_".rand(0,99).".".$extension;
$uploaded = $file_name->move($path, $updated_fileName);
echo $updated_fileName;
}
More details :
File upload through a modal using Ajax
This code checks if request has a file if yes then names it and then moves the files to a folder in public dir.
if($request->hasFile('modelpic')) {
$file = Input::file('modelpic');
//get file extension
$name = 'image'.$file->getClientOriginalExtension();
//move file to public/images dir
$file->move(public_path().'/images/', $name);
}
Images are submitted with multiple part request due to size use (Multipart-form-data) in form tag.
Like this,
<div class="card-block">
{!! Form::open(array( 'autocomplete' => 'off', 'id' => 'AddModel', 'url' => 'model/useradd', 'files' => true,'enctype' => 'multipart/form-data')) !!}
<div class="form-group">
<label for="picture">Picture</label>
#if( (new Jenssegers\Agent\Agent)->isMobile() )
{!! Form::file('image', ['id' => 'modelpic', 'accept' => 'image/*', 'capture' => 'camera']) !!}
#else
{!! Form::file('image', ['id' => 'modelpic']) !!}
#endif
<br/>
</div>
<div id="imagePreview" style="display: none;"></div> /** here I show preview of the image through JS */
<div class="form-group">
{!! Form::submit('Submit', array('id' => 'AddBtn', 'class' => 'btn btn-default' )) !!}
{!! Form::close() !!}
</div>

Laravel 5.1 MethodNotAllowedHttpException Error

I'm using resource controller , when i submit form through ajax , it is showing method not allowed exception.
View
{!! Form::open(array('route' => 'product.store','class' => 'form-horizontal','id' => 'productform','name' => 'productform','files' => true)) !!}
{!! csrf_field() !!}
<div class="form-group" style="padding-top: 20px">
<label for="productName" class="col-sm-3 control-label">Product name</label>
<div class="col-sm-9">
{!! Form::text('productName',null, array('id'=> 'productName','class'=>'form-control','placeholder'=>'Product name'))!!}
</div>
</div>
<div class="form-group">
<div class="col-sm-9 col-sm-offset-3">
{!! Form::submit('Save', array('class' => 'btn btn-primary btn-block')) !!}
</div>
</div>
{!! Form::close() !!}
AJAX
$("#productform").submit(function () {
var token = $('[name=_token]').val();
$.ajax({
type: 'POST',
url: 'product/store',
data: {
id: '4',
_token: token,
},
success: function (data) {
alert('success');
return false;
}
})
return false;
});
routes.php
Route::resource('product', 'ProductController');
What is the problem here...Any help is much appreciated.
in jquery
var BASEURL = $("#baseURL").val()
in html
<input type="hidden" id="baseURL" value="{{ url('') }}" >
when you try to store data in laravel your URL must be.
url: 'product',
try to go on your CMD and type:
php artisan route:list
and check the URI of product.store Name then that will be you url in your AJAX.
in AJAX
try to set url in AJAX to be route
$("#productform").submit(function () {
var token = $('[name=_token]').val();
$.ajax({
type: 'POST',
url: '{{ route("product.store") }}',
data: {
id: '4',
_token: token,
},
success: function (data) {
alert('success');
return false;
}
});
return false;
});

Is it required to form::open() tag in laravel 5.1?

I'm a little bit confused about Forms. Is Form::open() required to send it in controller? And I don't want to load it so I used AJAX.
View:
{!! Form::open(['route' => 'register', 'id' => 'register']) !!}
{!! Form::label('FirstName: ') !!} {!! Form::text('firstname', null, ['class'=> 'form-control']) !!}
{!! Form::submit() !!}
{!! Form::close() !!}
JS:
$('#register').on('submit', function(){
$.post('/register',{
data: {req: $(this).serialize()}
}).done(function(response){
console.log(response);
});
});
Your form submits because you are not preventing the default event via ajax. Your ajax should look like thos
$('#register').on('submit', function(e){
$.post('/register',{
data: {req: $(this).serialize()}
}).done(function(response){
console.log(response);
});
event.preventDefault();
});
Hope this help.

Ajax POST error using Laravel

I want to submit a form of checkboxes that represent the interests of an user. When clicking a checkbox, the value of the checked interest will be sent to the database "Followers" table and the user will begin following that interest. I couldn't find a way to have one form submit multiple rows, so i decided to make each checkbox a different form and use Ajax to send the information as the user goes through the form. However, When i attempt to make a POST using Ajax I get POST http://localhost/interest net::ERR_CONNECTION_REFUSED. or ERR 500. Can someone help me? I don't understand where i'm messing up. here is my code:
i have the meta tag
<meta name="_token" content="{{ csrf_token() }}"/>
html:
{!! Form::open(array('id'=> 'form2')) !!}
<div class = "form-group">
<div class="col-md-6">
{!! Form::label('title','Title:', ['class' => 'col-md-4 control-label']) !!}
{!! Form::checkbox('interest_id', '2', false, ['class' => 'formclick']) !!}
</div>
</div>
<input id = "submit" type="button" value="Click Me!" />
{!! Form::close() !!}
JS:
var base_url = 'http://localhost';
$('#submit').click(function(){
var interest = {
interest_id : $('.formclick').val()
}
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$.ajax({
type: 'POST',
url: base_url+'/interest',
data: interest,
dataType: 'JSON',
success: function() {
alert('new interest');
}
});
});
InterestController:
public function store(InterestRequest $interest)
{
$interest = new Follower(array(
'user_id' => $interest->get('interest_id'),
'follower_id' => Auth::id()
));
$interest->save();
}
Don't use the same variable name for an parameter and a local scope variable.
Are you using nginx or apache?
Have you setup your .htaccess file right?
What do you see when you go to http://localhost/interest/public
Enable the Laravel debug mode, there you have much more information which can be of help to you and us.
You should use proper path of URL to ajax call.
instead of use:
var base_url = 'http://localhost';
use:
var base_url = '{{ url() }}';
It will resolve your issue

Categories