I have created simple web application with laravel 5.8.
this is my project url http://localhost/test/public/home
web.php
Route::group(['middleware' => ['auth', 'preventBackHistory']], function() {
Route::get('home', 'HomeController#index')->name('home');
Route::post('generate_table.data', 'HomeController#generate_table')->name('generate_table.data');
});
I am calling this ajax into home.blade
"ajax": {
"url":"{!! route("generate_table.data") !!}",
"type": "POST",
"jsonpCallback": 'jsonCallback',
"dataType": "jsonp"
}
I haven't any issue with this ajax.it is loading data. If i navigate to http://localhost/test/public/generate_table.data?callback=jsonCallback , i am getting black screen with
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
If user navigate http://localhost/test/public/generate_table.data?callback=jsonCallback How to navigate back to /home?
.env
APP_DEBUG=false
Thank you.
You can redirect the user when the GET method is used.
// GET method will be redirected to home.
Route::get('generate_table.data', function () {
return redirect()->to('/');
});
// The POST method will be passed to the controller.
Route::post('generate_table.data', 'HomeController#generate_table')->name('generate_table.data');
Add this to your routes:
Route::get('generate_table.data', 'HomeController#index');
Related
I have a file upload form in vue and want to pass the file data to a laravel controller. The data is passed from page to store fine in vue, but I can't access it in my controller:
vue page:
update() {
this.$store.dispatch('uploadDocument', {
file: this.form.file,
})
},
store:
axios.post('/users/newDocument', {
file: data.file,
})
If I console.log data.file, I can see the file is passed to post method:
'File {name: 'test2.txt', lastModified: 1633600501434, lastModifiedDate:......'
Route:
Route::post('/users/newDocument', [UserController::class, 'store']);
controller:
public function store(Request $request)
{
return $request;
}
but nothing is returned, even if I do $request->file, or $request->hasFile('file'):
'{data: {…}, status: 200, statusText: 'OK', headers: {…}, config: {…}, …}'
Any ideas what I'm missing? Do I need to first build the form data? (new FormData()). I've tried adding _method: 'PATCH' to the form and adding the header: 'Content-Type': 'multipart/form-data', but still nothing.
FIX:
in vue, pass the form data:
const formData = new FormData();
formData.append('name', this.form.file.name);
formData.append('document_type', this.form.document_type);
in vue store:
axios.post('/users/newDocument', formData, {'content-type': 'multipart/form-data'})
laravel controller:
$request->get('name')
You need to build the FormData first and send it though axios Wwthout forgetting to modify the header as you started to do it.
i am typing text in text area
<input placeholder="DISCOUNT COUPON" type="text" id="coupon">
Sending that text to controller using ajax;
$.ajax({
type: "POST",
url: "applyCoupon",
data:{
coupon: $('#coupon').val(),
course_id: {{$course->id}},
_token: {{ csrf_token() }},
},
success: function(dataResult){
alert("success");} // why i am not GETTING this alert?
Controller:
public function applyCoupon(Request $request)
{
$result=new \stdClass();
$coupons = Coupons::select('discount_percentage')->where('coupon_code',$request->get('coupon'))
->where('course_id',$request->get('course_id'))
->get();
$course = Course::findOrFail($request->get('course_id'));
$discounted_price= ($course->price) - (($course->price)*($coupons[0]->discount_percentage)/100);
$result->val = $discounted_price;
$result->statusCode = 200;
return json_encode($result);
}
Web.php:
Route::post('course/applyCoupon', ['uses' => 'CoursesController#applyCoupon', 'as' => 'courses.applyCoupon']);
everything seems fine, but why success function is not running?
You should be using routes/api.php instead of routes/web.phpin the first place.
Also, log error by adding
...
error: function (request, error) {
console.log(error);
alert("Error");
},
That should give you a clue. Could be anything depending on your setup.
You're not using the full URL you setup in your routes/web.php
Change
url: "applyCoupon",
to
url: "course/applyCoupon",
or even better would be to use the route name you provided
url: "{{route('courses.applyCoupon')}}",
Give correct route to your ajax call
Pass this in your ajax url.
url: "{{ route('courses.applyCoupon' }}"
if still not working, then Check your network tab in inspect tool
Click on the ajax call and it will show you the detail on your right side.
post here what you are getting there.
You need to give the response in return of ajax call:-
use Response;
return response()->json(['message' => 'error', 'data' => $data]);
I have made a ajax call in laravel 5.4 following is the script
<script>
$(document).ready(function()
{
$("#btnLogin").click(function()
{
// var username = $('#username').val();
// var password = $('#password').val();
// var form = new FormData($('.login-form')[0]);
var form = $('.login-form').serializeArray();
$.ajax({
url: '/login',
type: 'POST',
dataType: 'JSON',
data: {form},
})
.done(function(resp){
console.log(resp);
})
.fail(function(resp){
console.log(resp);
})
.always(function(resp){
console.log(resp);
});
});
});
</script>
This is my web.php in routes folder
<?php
Route::match(['get', 'post'], '/login', function () {
return "hello";
});
It is showing the error in console log, i dont know why it is showing this. Firstly it was showing 404 not found then i realized that i had not defined in rotes then i defined in routes then it is showing this error.
POST http://www.example.com/login 500 (Internal Server Error)
If access this url through browser direct it is showing hello but if i am making through ajax it is not loading.
When you hitting through browser, you are requesting page with get request, however, through ajax, it goes through post.
im trying to submit a form via JsRoutes and ajax and i dont think that im getting to the controller ....
this is my routes
POST /submit controllers.Application.submit()
and this is my jsrouts function:
$('#submit').click(function() {
JsRoutes.controllers.Application.submit().ajax({
data : $("#contact-form").serialize(),
url: '#{Application.submit()}',
success : function(data) {
alert("Succsses");
},
error : function(err) {
alert("error");
}
});
});
this is what im sendig to the server
http://localhost:9000/?name=ajax&lastName=aaa&email=miko5054%40hotmail.com&phone=453534
what im doing wrong here ???
The #{Application.submit()} code is incorrect. It should be #{routes.Application.submit()}.
But if you use the javascript router JsRoutes.controllers.Application.submit(), you don't need to specify the url inside the ajax() call. You can just remove the url:... line and everything should work fine.
i'm making an ajax call from my laravel blade view like this:
function deleteUser(user_id)
{
$.ajax({
url: '{!! route('users.delete', ['id' => user_id]) !!}',
type: 'DELETE',
data: {_token: '{!! csrf_token() !!}'},
dataType: 'JSON',
success: function (data) {
console.log(data);
}
});
}
and in my routes.php file i defined the route:
//routes.php
Route::delete('users/{id}/delete', 'UserController#delete')->name('users.delete');
where i'm just refreshing the page an error was occured:
Use of undefined constant user_id- assumed 'user_id'
i realized that the user_id parameter is injected by the wrong way inside the route() method within javascript block.
is there a way to inject parameters in the url of ajax call inside the route method of laravel?
You can't use Laravel helpers in your JS, unless your JS code building dynamically (which is bad idea). So just use manually built URLs.
url: 'users/145/delete',
You can trying doing it this way '{{url("users/$user->id/delete")}}'; your route will pick it up and redirect where it needs to go