I'm submitting my form using ajax in laravel
Output:
{"message":"The given data was invalid.","errors":{"name":["The name field is required."],"image":["The image field is required."]}}
View:
{{ Form::open(array('route' => 'ajax-add-record','enctype' => 'multipart/form-data','files'=> true,'class'=>'add','id'=>'frmadd')) }}
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<h2 class="card-inside-title">Name</h2>
<div class="form-line focused">
{{ Form::text('name','',['class'=>'form-control','placeholder'=>'Name','id'=>'name']) }}
</div>
</div>
</div>
</div>
</div>
<div class="row clearfix">
<div class="col-sm-6">
<div class="form-group">
<h2 class="card-inside-title">Image</h2>
<div class="form-line focused">
{{ Form::file('image',['class'=>'form-control']) }}
</div>
</div>
</div>
</div>
<button class="btn btn-info add_button btn-xs p-3 hide" type="button"><i class="material-icons">add</i> Add</button>
</div>
{{ Form::close()}}
Script:
$('#frmadd').submit(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: APP_URL+'/add',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(response)
{
},
error: function(data)
{
}
});
});
Related
Laravel Post html but as raw text
i'm use tinymce and normal input
i try to normal post and get with url and ajax
<div class="modal fade" id="addpromotion" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="addpromotionLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<form action="{{ route('admin.blog.create') }}" id="addpromotionform" method="post" enctype="multipart/form-data">
#csrf
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<div class="modal-header">
<h1 class="modal-title fs-5" id="addpromotionLabel">เพิ่มโปรโมชั่น</h1>
{{-- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> --}}
</div>
<div class="modal-body">
<div class="mb-3 mx-5">
<input type="file" class="form-control" name="image" style="border-radius: 15px;">
</div>
<div class="mb-3 mx-5">
<input type="text" name="title" class="form-control" placeholder="Title" style="border-radius: 15px;">
</div>
<div class="mb-3 mx-5">
<input type="text" name="description" class="form-control" placeholder="Description" style="border-radius: 15px;">
</div>
<div class="mb-3 mx-5">
<textarea id="tinymcecreate" class="tinymce" name="body"></textarea>
</div>
<input type="hidden" name="type" value="promotion">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger">บันทึก</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">ปิด</button>
</div>
</form>
</div>
</div>
</div>
body=%3Cp%3E%3Cstrong%3Ecustom%3C%2Fstrong%3E%3C%2Fp%3E
when console.log ( data before post )
_token=bNPyuZroL8QIJN3beZJyFYaVELWIyNb9kpvX48Zn&csrf_token=bNPyuZroL8QIJN3beZJyFYaVELWIyNb9kpvX48Zn&title=qwqgqw&description=qgqg&body=%3Cp%3E%3Cstrong%3Ecustom%3C%2Fstrong%3E%3C%2Fp%3E&type=promotion
$('#addpromotionform').on('submit', function(ed) {
tinymce.triggerSave();
ed.preventDefault();
var TinyAjaxPost = $('#addpromotionform').serialize();
var formData = new FormData(this);
console.log(TinyAjaxPost);
$.ajax({
type: "post",
url:'{{URL::to("/admin/blog/create")}}',
data: formData,
cache:false,
dataType: 'html',
contentType: false,
processData: false,
success: function(data) {
console.log('success'+Object.values(data.message));
},
error: function(error) {
console.log('error'+error);
}
});
});
but when post to controller i check with dd($request)
body don't have html tag but have only raw text ... custom
public function admin_blog_create(Request $request)
{
$file_name = time() . '.' . request()->image->getClientOriginalExtension();
$request->image->move(public_path('image/tinymce'), $file_name);
$tiny = [
'image' => $file_name,
'title' => $request->title,
'description' => $request->description,
'body' => $request->body,
'type' => 'blog',
];
blog::create($tiny);
return response()->json(['status'=>true, 'message' => $request->body]);
/* return redirect()->back(); */
}
and i try to use Get with url when check data with dd($request) have only raw text custom
Tools
Laravel 9
TinyMCE 6
How i post or get with full html to database ?
XSS Protection it is a problem.
i'm try to disable xss in controller
$this->middleware('XSS');
Can post ( request ) html data to database
enter image description here
Type this code if you are experiencing error 419
// Ajax CSRF Setup Code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
The correct way to send, in addition to viewing the data in the console
$('#addpromotionform').on('submit', function(ed) {
ed.preventDefault();
//console log data
var TinyAjaxPost = $('#addpromotionform').serialize();
var copy = $("#addpromotionform iframe").contents().find('#tinymce').clone();
copy = $(copy).html();
console.log(TinyAjaxPost,copy);
$.ajax({
type: "post",
url:'{{URL::to("/admin/blog/create")}}',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log('success'+Object.values(data.message));
},
error: function(error) {
console.log('error'+error);
}
});
});
I am using Dropzone.js to upload multiple images in Laravel. Though Image is uploaded without any error, request is empty. Any solution for this?
HTML code
<form class="form-horizontal" id="form" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="col-sm-2 control-label">ISSUE DATE / VOLUME NO</label>
<div class="col-sm-10"><input type="text" class="form-control" name="valume_no" value={{ old('valume_no') }}></div>
</div>
<div class="dropzone" id="my-dropzone">
<div class="dz-message">
<div class="col-xs-8">
<div class="message">
<p>Drop files here or Click to Upload</p>
</div>
</div>
</div>
<div class="fallback">
<input name="featured_file" type="file[]" multiple />
</div>
</div>
<div class="form-group">
<div class="col-sm-8 col-sm-offset-2">
<button class="btn btn-primary" type="submit">Done</button>
</div>
</div>
</form>
Dropzone configuration
Dropzone.autoDiscover = false;
$(document).ready(function () {
$("#my-dropzone").dropzone({
url: '{{ url("/news/uploadimgsaddmode") }}',
headers: {
'x-csrf-token': "{{ csrf_token() }}",
},
method: 'post',
paramName: "file",
maxFiles: 100,
maxFileSize: 100,
acceptedFiles: ".jpeg,.jpg,.png",
uploadMultiple: true,
parallelUploads: 100,
previewTemplate: document.querySelector('#preview').innerHTML,
addRemoveLinks: true,
dictRemoveFile: 'Remove file',
dictFileTooBig: 'Image is larger than 16MB',
timeout: 10000,
success: function (file, response) {
console.log(response);
}
});
});
Laravel Controller
public function uploadimgsaddmode(Request $request){
return Response::json(['message' => $request], 200);
}
Response
{"message":[{}]}
i want to make delete confirmation laravel with Modal,
i call route laravel in ajax, but why the route is not found .
this is my route in laravel
Route::delete('delete-product/{productId}', 'StoreController#hapus')->name('product.delete');
this is my ajax delete..
$(document).on('click', '.delete-modal', function() {
$('.modal-title').text('Delete');
$('#id_delete').val($(this).data('productId'));
$('#deleteModal').modal('show');
productId = $('#id_delete').val();
});
$('.modal-footer').on('click', '.hapus', function() {
$.ajax({
type: 'DELETE',
url: 'delete-product/' + productId,
data: {
'_token': $('input[name=_token]').val(),
},
when i click icon trash,, modal is show, but in modal when i click delete button then inspect element in browser my route is not found
this is inspect element
Request URL: http://localhost:8000/delete-product/
Request Method: DELETE
Status Code: 404 Not Found
Remote Address: 127.0.0.1:8000
Referrer Policy: no-referrer-when-downgrade
why the URL just delete/product .... not include ID ,,
even though my url in ajax called like this
......
url: 'delete-product/' + productId,
.....
this is my blade code
#if(sizeof($resp->content) > 0)
<ul class="the-product">
#foreach($resp->content as $item)
<li>
#if(isset($store) && $store->storeId == $item->store->storeId)
<i class="icofont-ui-love"></i>
#else
<a class="btn btn-danger delete-modal"><i class="fa fa-trash" data-id="{{$item->productId}}"></i></a>
<a class="btn btn-danger" onclick="return myFunction();" href="{{url('edit.product', $item->productId)}}"><i class="icofont-ui-edit"></i></a>
{{-- <i class="icofont-ui-edit"></i> --}}
{{-- <i class="icofont-ui-delete"></i> --}}
#endif
{{-- onclick="ajaxContent(event, this);" --}}
<a href="productDetail/{{ $item->productId }}" class="the-item #if($item->discount > 0)on-promo #endif">
#if($item->discount > 0)
<div class="prod-rib">{{ $item->discount }}% Off</div>
#endif
<img data-src="#if($item->imageId != null){{ config('constant.showImage').$item->imageId }}#else{{ asset('images/no-image-available.png') }}#endif"
src="#if($item->imageId != null){{ config('constant.showImage').$item->imageId }}#else{{ asset('images/no-image-available.png') }}#endif"
alt="{{ $item->productNm }}">
<div class="prod-name">{{ $item->productNm }}</div>
<div class="prod-rev">
#for($i=0; $i<5;$i++)
#if($i<$item->reviewRate)
<img src="{{asset('img/kopi-on.svg')}}" />
#else
<img src="{{asset('img/kopi.svg')}}" />
#endif
#endfor
<span>{{ $item->reviewCount }} ulasan</span>
</div>
<div class="prod-price">
#if($item->discount > 0)
<span>Rp. {{ number_format($item->price,0,',','.') }}</span> Rp. <i>{{ APIHelper::discountPrice($item->discount, $item->price) }}</i>
#else
Rp. <i>{{ APIHelper::discountPrice($item->discount, $item->price) }}</i>
#endif
</div>
</a>
Add to cart <i class="icofont-cart"></i>
{{-- //onclick="ajaxContent(event, this);" --}}
<a href="{{url('/store-detail/'.$item->store->storeId)}}" class="the-store">
<img src="#if($item->store->storePic != null){{ config('constant.showImage').$item->store->storePic }}#else{{ asset('images/no-image-available.png') }}#endif" />
{{ $item->store->storeNm }}
<span>{{ $item->store->percentFeedback }}% ({{ $item->store->totalFeedback }}
feedback)</span>
</a>
</li>
#endforeach
</ul>
<ul class="pagination">
<li class="disabled">
<span><i class="icofont-rounded-double-left"></i></span>
</li><li class="disabled">
<span><i class="icofont-rounded-left"></i></span>
</li>
{{-- active --}}
#for ($i = 0; $i < $resp->totalPages && $i < 5; $i++)
<li class="" onclick="ajaxContent(event, this,null,{'key':'page','value':{{$i+1}} })">
<span>{{$i + 1}}</span>
</li>
#endfor
<li>
<i class="icofont-rounded-right"></i>
</li>
<li>
<i class="icofont-rounded-double-right"></i>
</li>
</ul>
#else
<div class="container clearfix">
<div class="style-msg errormsg mt-5">
<div class="sb-msg"><i class="icon-remove"></i><strong>Maaf</strong>, pencarian anda tidak cocok dengan
produk apapun. Silahkan coba lagi
</div>
</div>
</div>
#endif
<!-- Modal form to delete a form -->
<div id="deleteModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
<h3 class="text-center">Are you sure you want to delete the following post?</h3>
<br />
<form class="form-horizontal" role="form">
<div class="form-group">
<label class="control-label col-sm-2" for="id">ID:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="id_delete" disabled>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="title">Title:</label>
<div class="col-sm-10">
<input type="name" class="form-control" id="title_delete" disabled>
</div>
</div>
</form>
<div class="modal-footer">
<button type="button" class="btn btn-danger hapus" data-dismiss="modal">
<span id="" class='glyphicon glyphicon-trash'></span> Delete
</button>
<button type="button" class="btn btn-warning" data-dismiss="modal">
<span class='glyphicon glyphicon-remove'></span> Close
</button>
</div>
</div>
</div>
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).on('click', '.delete-modal', function() {
$('.modal-title').text('Delete');
$('#id_delete').val($(this).data('productId'));
$('#deleteModal').modal('show');
productId = $('#id_delete').val();
});
$('.modal-footer').on('click', '.hapus', function() {
$.ajax({
type: 'DELETE',
url: 'delete-product/{productId}',
data: {
'_token': $('input[name=_token]').val(),
},
success: function(data) {
toastr.success('Successfully deleted Post!', 'Success Alert', {timeOut: 5000});
$('.item' + data['id']).remove();
$('.col1').each(function (index) {
$(this).html(index+1);
});
}
});
});
</script>
how to write URL in ajax ?
plis HELP..
In your case, in the following code :
$(document).on('click', '.delete-modal', function() {
$('.modal-title').text('Delete');
$('#id_delete').val($(this).data('productId'));
$('#deleteModal').modal('show');
productId = $('#id_delete').val();
});
ProductId is a local variable having scope function scope. You can not refer it outside unless you declare it globally at the top.
When you try to refer it directly later, it will not be having any value(undefined).
Secondly, You need to change
url: 'delete-product/{productId}'
with
url: '/delete-product/' + productId,
So below is the code :
jQuery(document).ready(function($){
$(document).on('click', '.delete-modal', function() {
$('.modal-title').text('Delete');
$('#id_delete').val($(this).data('productId'));
$('#deleteModal').modal('show');
});
$('.modal-footer').on('click', '.hapus', function() {
var productId = $('#id_delete').val();
$.ajax({
type: 'DELETE',
url: '/delete-product/' + productId,
data: {
'_token': $('input[name=_token]').val(),
},
success: function(data) {
toastr.success('Successfully deleted Post!', 'Success Alert', {timeOut: 5000});
$('.item' + data['id']).remove();
$('.col1').each(function (index) {
$(this).html(index+1);
});
}
});
});
});
I am using an ajax request on click to trigger a controller JsonResult in MVC. When I click, I receive an HTML response instead of JSON, here is my code:
$('.platform-list-item').click(function (e) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "#Url.Action("PlatformClick", "To")",
data: JSON.stringify({ "platform": $(this).find(".platform-click").val() }),
success: function (data) {
console.log("worked!");
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
});
The $(this).find(".platform-click").val() is a string value. Here is my controller code in ToController.cs:
[HttpPost]
public JsonResult PlatformClick(string platform)
{
Debug.WriteLine("PlatformClick");
Debug.WriteLine(platform);
return Json("test");
}
Here are the two new events that show up in my Network Tab through Developer tools. Where did I go wrong? Thank you!
EDIT: Adding HTML View per request:
<div class="platform-to-container">
<div id="platform-container">
<div class="album-container">
<div class="album-img-container">
<img crossorigin="anonymous" id="album-img" src="https://i1.sndcdn.com/artworks-9vhl8uXrclxW-0-t500x500.jpg" />
</div>
</div>
<div class="platform-links-container">
<div class="artist-song">#Model.Album.AlbumName</div>
<div class="artist-song-container">
<img class="artist-img" src="https://i1.sndcdn.com/avatars-000438614124-cca9kq-t500x500.jpg" />
<div class="artist-name">#Model.Artist.ArtistName</div>
</div>
<div class="platform-list-container">
#if (!String.IsNullOrWhiteSpace(Model.Album.SpotifyLink))
{
<div class="platform-list-item">
<div class="platform-logo-container">
<img class="platform-logo" src="https://s3.amazonaws.com/unlink/platform-images/music-service_spotify_v3.svg" />
</div>
<div class="platform-btn-container">
<div class="link-btn"><i class="fas fa-play"></i>Stream</div>
</div>
<input type="hidden" class="platform-click" value="spotify" />
</div>
}
#if (!String.IsNullOrWhiteSpace(Model.Album.ItunesLink))
{
<div class="platform-list-item">
<div class="platform-logo-container">
<img class="platform-logo" src="https://s3.amazonaws.com/unlink/platform-images/music-service_itunes_v2.svg" />
</div>
<div class="platform-btn-container">
<div class="link-btn"><i class="fas fa-play"></i>Download</div>
</div>
<input type="hidden" class="platform-click" value="itunes" />
</div>
}
#if (!String.IsNullOrWhiteSpace(Model.Album.AppleMusicLink))
{
<div class="platform-list-item">
<div class="platform-logo-container">
<img class="platform-logo" src="https://s3.amazonaws.com/unlink/platform-images/music-service_applemusic_v2.svg" />
</div>
<div class="platform-btn-container">
<div class="link-btn"><i class="fas fa-play"></i>Stream</div>
</div>
<input type="hidden" class="platform-click" value="appleMusic" />
</div>
}
</div>
</div>
</div>
</div>
I am trying to send form with upload file and multipart/form-data encoding using AJAX. I am using this form:
{!! Form::model($user, ['method' => 'PATCH', 'url' => ['/administrator/users', $user->id], 'class' => 'form-horizontal', 'files' => 'true', 'id' => 'userEdit']) !!}
<div class="modal-body">
<div class="form-group">
<label class="col-sm-3 control-label">Avatar:</label>
<div class="col-sm-9">
<img src="/dashboard/assets/img/avatar/{{ $user->profile->avatar }}" class="img-circle m-b" />
<input type="file" name="avatar" />
</div>
</div>
<hr />
<div class="form-group">
<label class="col-sm-3 control-label">Name:</label>
<div class="col-sm-9">
<input type="text" name="first_name" value="{{ $user->profile->first_name }}" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Surname:</label>
<div class="col-sm-9">
<input type="text" name="last_name" value="{{ $user->profile->last_name }}" class="form-control" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-info" data-user-id="{{$user->id}}">Save</button>
</div>
{!! Form::close() !!}
I try to send data with Ajax like this:
$('#editUser').submit('#userEdit', function(event) {
event.preventDefault();
$.ajax({
type: 'PATCH',
url: '/administrator/users/1',
data: new FormData(userEdit),
processData: false,
contentType: false,
mimeType: "multipart/form-data",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data) {
alert(data);
},
error: function(xhr, str){
alert(str);
}
});
});
And in result, I cannot read inputs from request in controller. It returns an empty array.
public function update($id, Request $request){
dd($request->all());
}
I think that I'm doing something wrong with sending multipart data. How to send it correctly?
It seems that you aren't adding FormData properly and your event seems to be broken, you should add the data in ajax like this:
$('#editUser').on('submit', function(event) {
event.preventDefault();
var form = $(this); // You need to use standard JS object here
var formData = new FormData(form);
$.ajax({
type: 'PATCH',
url: '/administrator/users/1',
data: formData,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data) {
alert(data);
},
error: function(xhr, str){
alert(str);
}
});
});
Hope this helps!