I'm facing a very weird issue. I'm trying to store photo using Jquery AJAX.
My Route
Route::resource('photo', 'PhotoController');
My Blade Code
<form id="photo_form" enctype="multipart/form-data" onsubmit="return false;">
<input type="file" name="file" id="photo_file" accept="image/gif, image/jpeg, image/png"/>
<input type="submit" class="btn btn-outline-dark" value="Upload and Get Link"/><br/>
</form>
My View AJAX Code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#photo_form").submit(function () {
var formData = new FormData(this);
$.ajax({
url: "{{route('photo.index')}}",
method: "POST",
data: formData,
contentType: false,
cache: false,
processData: false,
success: function (data) {
console.log(data);
if (data.status) {
}
},
error: function (error) {
alert(error.responseText);
}
});
});
My Controller Code
public function store(Request $request) {
return [true];
}
when ajax call is called, it gives me 2 issue in network tab of firefox
POST https://fb.srdlict.com/photo
301 Moved Permanently
And
403 Forbidden
GET https://fb.srdlict.com/photo/
Seems like the ajax request is forwarded to /photo/ route somehow and then 403 happened. Other routes are working fine. Just only this route. Can anyone help me?
Related
I have in my view one input type "file", so I would like to get this file with jquery and send to my controller in Laravel, but, I don't see this file in debug
<form onSubmit="return false;" method="post" id="myForm" enctype=“multipart/form-data”>
#csrf
<label for="input-file-max-fs">Foto do perfil</label>
<input type="file" name="foto" id="foto" class="dropify #error('foto') is-invalid #enderror" data-max-file-size="3M" />
</form>
in the JS
$('.update).on('click', function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var dados = {
foto: $('input[name=foto]').val(),
.....
}
$.ajax({
method: 'PUT',
dataType: 'JSON',
url: '../perfil/editarusuario/',
data: dados,
success: function(res) {
console.log(res);
}
});
})
and in my Controller I trying to get the file, but no success
$file = $request->file('foto');
$file = $request->hasFile('foto')
$file = $request->file('foto')->isValid()
none of theses work
You should use "new FormData()" and "contentType",
here is the answer to this;
https://stackoverflow.com/a/21045034/14843602
I'm trying to create a personal messaging system in laravel, and apart of this system is being able to send messages in a form without refreshing the entire page.
I've been following some youtube tutorials, and this is the Ajax script I have so far.
<form id="form{{$dm->id}}">
{{ csrf_field() }}
<input id="message" placeholder="Send a message" style="border-radius: 0px;" type="username" class="form-control" name="message">
<script>
$('form{{$dm->id}}').ready(function (){
$('form{{$dm->id}}').on('submit', function( event ) {
event.preventDefault();
$.ajax({
type: 'post',
url: '{{ route("sendMessage", $dm->id) }}',
data: $('form{{$dm->id}}').serialize(),
success: function(response){
alert('suces')
},
error: function(response){
alert('failure')
}
});
});
});
</script>
</form>
Instead of sending a POST request to the controller, it sends a GET request and just redirects.
This is my first time messing with Ajax/Javascript in general, so I don't know exactly why this isn't working.
Controller script:
public function sendM(Request $request, $id)
{
$validatedData = $request->validate([
'message' => 'required|string|max:255|min:4',
]);
$dm = Dm::find($id);
$mess = new Message;
$mess->Authid = Auth::user()->id;
$mess->Userid = $dm->Userid;
$mess->Dmid = $dm->id;
$mess->message = $request->input('message');
$dm->messages()->save($mess);
$dm->touch();
}
Route entry:
Route::post('/sendmessage/id{id}', 'SettingsController#sendM')->name('sendMessage')->middleware('verified');
Any help is very much appreciated! (Note: Sorry if it is something really obvious)
In the $.ajax call, you need to set the method to post instead of the type.
$.ajax({
method: 'post',
url: '{{ route("sendMessage", $dm->id) }}',
data: $('form{{$dm->id}}').serialize(),
success: function(response){
alert('suces')
},
error: function(response){
alert('failure')
}
});
As an aside, jquery is often considered to be on the way out. You may want to look into what some alternatives to jquery would look like, such as vue.js or react. Specific to the ajax aspect, Laravel has built in axios support.
Not sure if it solves your problem, but you must also add the csrf token to the headers:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
(if the token is in a meta tag of course)
An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0.
<form id="form{{$dm->id}}">
{{ csrf_field() }}
<input id="message" placeholder="Send a message" style="border-radius: 0px;" type="username" class="form-control" name="message">
<script>
$('form{{$dm->id}}').ready(function (){
$('form{{$dm->id}}').on('submit', function( event ) {
event.preventDefault();
$.ajax({
type: 'POST', //Check your JQ version.
method: 'POST', //Check your JQ version.
contentType:"multipart/form-data; charset=utf-8",
//url: '{{ route("sendMessage", $dm->id) }}',
url: '{{ route("sendmessage", $dm->id) }}',
data: $('form{{$dm->id}}').serialize(),
success: function(response){
alert('suces')
},
error: function(response){
alert('failure')
}
});
});
});
</script>
</form>
I am trying to delete image from folder using ajax and in route using delete method .In controller trying to delete image using image name in laravel.
Route:
Route::delete('remove-social/{filename}', 'Webadmin\Socials#removesocial');
Controller:
public function removesocial($filename){
File::delete('public/assets/uploads/Social/' . $filename);
}
View :
<a href="javascript:removesocialimage()" style="color: white;text-decoration: none;" class="btn btn-red">
<i class="glyphicon glyphicon-trash "></i> Remove</a> </label>
<script>
function removesocialimage() {
if (j('#file_name').val() != '')
if (confirm('Are you sure want to remove social icon?')) {
j('#loading').css('display', 'block');
var form_data = new FormData();
form_data.append('_method', 'DELETE');
form_data.append('_token', '{{csrf_token()}}');
j.ajax({
url: "remove-social/" + j('#file_name').val(),
data: form_data,
type: 'POST',
contentType: false,
processData: false,
success: function (data) {
j('#preview_image').attr('src', '{{URL::to('/public/assets/Webadmin/images/attach-1.png')}}');
j('#file_name').val('');
j('#loading').css('display', 'none');
},
error: function (xhr, status, error) {
alert(error);
alert(xhr.responseText);
}
});
}
}
</script>
Include this in your views head:
<meta name="csrf-token" content="{{ csrf_token() }}">
And do this ajax setup before making network calls:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
try to change route delete to post method
Route::post('remove-social/{filename}', 'Webadmin\Socials#removesocial');
if you want to used delete method then your ajax look like
add in head html tag
<meta name="csrf-token" content="{{ csrf_token() }}">
js code
j.ajax({
url: "remove-social/" + j('#file_name').val(),
data: form_data,
headers: {
X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'DELETE', //POST TO DELETE
contentType: false,
processData: false,
success: function (data) {
j('#preview_image').attr('src', '{{URL::to('/public/assets/Webadmin/images/attach-1.png')}}');
j('#file_name').val('');
j('#loading').css('display', 'none');
},
error: function (xhr, status, error) {
alert(error);
alert(xhr.responseText);
}
});
While trying to use ajax request in my application using Laravel 5.6 I've found that the ajax request is not triggering.
My Controller code
class AjaxController extends Controller
{
function index(Request $request)
{
$msg = "Sample Messgae";
return response()->json(['msg' => $msg)]);
}
}
The Route,
web.php
Route::post('/message','AjaxController#index');
Route::get('/sample','UserRedirectController#ajaxRedirect');
The view
<input type="text" name="ajax" id="ajax">
<input type="text" name="_token" value="{{csrf_token()}}" id="token" hidden>
<button id="save" onclick="ajaxRequestFun();">Show</button>
<span id="cont"></span>
Finally the script
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
});
functon ajaxRequestFun()
{
$.ajax({
type : 'POST',
url : '/message',
data : {'_token': {{csrf_token()}} },
success:function(res){
alert("success");
}
});
}
</script>
Finally found some solution,
I've just added a meta tag to the view head tag just like.
<meta name="token" content="{{csrf_token()}}">
then at the JavaScript side formed the data to send using,
var pass= {'_token':$('meta[name="token"]').attr('content'),
'MessageContent': document.getElementById("message").value,
};
and initiated the ajax call normally with data: parameter as variable pass which I've created,
My ajax code is something like,
$.ajax({
type:'POST',
url:'{{url("/message")}}',
datatype:'json',
data: pass,
success:function(data){
$("#bubble").html(data);
}
}).fail(function(jqXHR, textStatus, error){
alert(jqXHR.responseText);
});
what I've found important is,
Use of the meta tag with the csrf_token() key
what else is as same as that of the other frameworks,
I try to post an uploaded file via ajax to php.
HTML:
<form id="uploadForm" name="uploadForm" action="#" enctype="multipart/form-data">
<input id="name" name="name" class="form-control" type="text" />
<input id="csv" name="csv" type="file" />
<input id="CSVUpload" type="submit" class="btn btn-default" name="Submit" value="Hochladen" />
JS
$("#uploadForm").submit(function () {
var formData = new FormData();
formData.append( 'csv', $( '#csv' )[0].files[0] );
formData.append( 'name', $( '#name'));
jQuery.ajax({
url: "../lib/import.php",
data: formData,
type: "POST",
success: alert('erfolgreich'),
error: alert('Fehler'),
cache: false,
contentType: false,
mimeType: 'multipart/form-data',
processData: false
});
});
and then i try to get the form data in PHP:
$_FILES['csv']
$_POST['name']
But the Ajax call completes with success and error... I'm confused...
The PHP file will not executed correctly...
Thanks for your help!
You aren't assigning functions to success or error.
You are calling the alert function immediately and then assigning its return value.
You need to create new functions to assign to success and error.
success: function () { alert('erfolgreich') },
error: function () { alert('Fehler') },
You are also calling the function as a submit handler, but aren't preventing the normal form submission. Consequently, the browser will load a new page before processing the response to the Ajax request.
$("#uploadForm").submit(function (event) {
event.preventDefault();
Try restructuring your AJAX call with your success and failure code like this:
$.post('../lib/import.php', formData).done(function() {
console.log('done');
}).fail(function() {
console.log('error');
});
See http://api.jquery.com/jquery.post/ for more examples.