Laravel error 405(Method Not Allowed) Ajax Posting - javascript

Hello i wnat to send my data with ajax to my controller.
My CODE
AJAX
$.ajax( {
type:'POST',
header:{
'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content')
},
url:"{{route('race.post')}}",
data:{
_token: "{{ csrf_token() }}",
dataType: 'json',
contentType:'application/json',
}
})
.done(function() {
alert('success');
})
.fail(function() {
alert("error");
});
CONTROLLER
public function Points(Request $request){
$test = $request->input('data');
return "$test";
}
ROUTE
Route::post('updateC', ['uses' =>'RacesController#Points', 'as' => 'race.post']);
And there are the errors what i get.
Console
Network-preview
Network-Response

I just removed the slash at the end of url and it began working...
/managers/games/id/push/ to:
$http({
method: 'POST',
url: "/managers/games/id/push",

add this one in your layout.blade file
<meta name="csrf-token" content="{{ csrf_token() }}">
then use this one in your js code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
i hope this will help!!

First thing is we put two routes in one for displaying view and another for post ajax. So simple add both routes in your route file.
routes/web.php
Route::get('ajaxRequest', 'RacesController#Points');
Route::post('ajaxRequest', 'RacesController#Points');
Include this meta tag inside your view
<meta name="csrf-token" content="{{ csrf_token() }}" />
Include javascript code inside your ajax call
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

Since you are working in a JavaScript file and not in a Blade file, the route() helper method is not working, and the route 'race.post' isn't parsed to an url.
Try to change the url to this:
url: '/updateC'
When you want to use the route() helper in your JavaScript, you have to add the script to a Blade file, and json_encode the value, you can read more about this in this answer.

I have different way to use it:
AJAX
data = {
selectmanufacturer: selectmanufacturer,
categories: selectCategory,
_token: "{{csrf_token()}}",
productName: productName
};
$.ajax({
url: '{{URL::to('/all-products-data')}}',
type: 'POST',
dataType: 'json',
data: data,
success: function (response) {
},
error: function (response) {
alert(response);
}
});
Controller:
public function Points(Request $request){
$test = $request->all();
return "$test";
}
I hope It will be helpful to you

The URL you’re posting to doesn’t look right in the console output you posted. In your AJAX code, you have this:
url:"{{route('race.post')}}"
But that’s just getting interpreted as is, it’s not getting interpreted as the value of that route in Laravel.
You’ll need to make sure that your JavaScript code is in a Blade template if you want Blade tags parsed.

not type: "POST", method :'POST" try the below code i have modified. ref: Reference Link
HTML code
<button onClick="onBtnClick()" data-url="{{route('race.post')}}"></button>
Updated Code
function onBtnClick(){
var token = $('meta[name="csrf-token"]').attr('content');
var url = $(this).attr("data-url");
$.ajax( {
method:'POST',
header:{
'X-CSRF-TOKEN': token
},
url: url,
data:{
_token: token,
dataType: 'json',
contentType:'application/json',
}
})
.done(function() {
alert('success');
})
.fail(function() {
alert("error");
});
}

Check if your laravel route is correctly set for this request.
In my case, I had a $.ajax url: "crop-image-upload" and a Route::post('crop-image-upload ', 'CropImageController#uploadCropImage');
But the request was sent to http://127.0.0.1:8000/news/crop-image-upload
So I had to change my route to Route::post('/news/crop-image-upload ', 'CropImageController#uploadCropImage');
So, in your case, try to add a literal url on ajax like this:
url:"/races/updateC"
and add 'races/' in the route like this:
Route::post('/races/updateC', ['uses' =>'RacesController#Points', 'as' => 'race.post']);

Related

JQuery doesn't work after adding ajax (Node.js, PUG)

I have been trying to add like functionality to my blog posts website.
When i click on the numbers of like link it should run ajax call.
In my server.js file i have a function that receives post request updates number of likes for the given post in mongodb database.
I have set name attribute of the link to equal post_id so that i can modified that post in databse.
html
head
style
include ../styles/home.css
link(rel='stylesheet', href='https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css')
script(src='https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js')
script(src='https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js')
script.
$(document).ready(function(){
$('.number_of_likes').click(function(e){
e.preventDefault();
alert('This part wont run');
$.ajax(
type: 'POST',
url: '/like',
data: {'post_id' : $(this).attr('name')},
success: function(result){
alert('it works');
},
dataType: 'json'
);
});
});
h2 Welcome to the main page
br
br
br
br
br
mixin postCard(postData)
.post_container
.row
.col.s12.m6
.card.blue-grey.darken-1
.card-content.white-text
span.card-title #{postData.title}
p= postData.content
.card-action
a(href='#') #{postData.username}
a(href='/delete_post/'+postData._id) Delete
a(href='' name=postData_id class='number_of_likes') #{postData.likes}
each post in result
+postCard(post)
But click event doesn't get fired.
The issue is probably because this is invalid syntax causing the entire application to come to a halt:
$.ajax(
type: 'POST',
url: '/like',
data: {'post_id' : $(this).attr('name')},
success: function(result){
alert('it works');
},
dataType: 'json'
);
You need to pass it as an object with the data between { and } like this:
$.ajax({
type: 'POST',
url: '/like',
data: {'post_id' : $(this).attr('name')},
success: function(result){
alert('it works');
},
dataType: 'json'
});

Ajax request to laravel backend results in 404

I never made an ajax request using laravel so it's different than just plain php.
This is my script that is attached on a dropdown onchange:
function createcomploadtemplate(){
var ifprefix = $("#createcomploadtemplatedropdown").find("option:selected").text();
var getidtemplate = $('#createcomploadtemplatedropdown').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: 'ajaxfixedcompany',
data: {getidtemplate:getidtemplate,ifprefix:ifprefix},
dataType: 'json',
encode : true,
success: function(data){
alert(data.success);
}
});
}
This is my route
Route::post('ajaxfixedcompany',['middleware' => 'auth', 'as' => 'ajaxfixedcompany', 'uses' => 'AjaxController#ajaxfixedcompany']);
And this is the function
public function ajaxfixedcompanyget(Request $request){
$response = array(
'status' => 'success',
'msg' => $request->message,
);
return response()->json($response);
}
If i use ajax url /ajaxfixedcompany instead of ajaxfixedcompany in chrome devtools i get "The page doesnt exist" with error 404
And without the / i get this:
EDIT: OMG...I think i just needed a break from all this. I have 2 controllers. 1 for POST and 1 for GET. i am requesting a POST while in my controller i only have my GET function created... It works again. lmfao
you can do this with csrf token.
$.ajax({
type: "POST",
url: "url/update",
dataType: 'json',
data: 'id=' + id+ '&_token={{csrf_token()}}',
Hope it helps.
Well i just needed a break. After that 1hour break i came back and noticed that i am making a post request, while it is also called in my route, but i had a typo in my controller....silly me... lmfao

Ajax Post to Laravel - CSRF Token Mismatch

I am trying to post data to Laravel backend with ajax, however I am getting 'CSRF token mismatch' error.
First, I've placed token in html (in body but outside its form because it's not the whole form, its only 2 elements to be posted):
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
Then in 'document ready', I try to post the data with ajax.
data["_token"] = jQuery('#token').val();
// Also tried this:
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': jQuery('#token').val()
}
})
console.log(data) // returns the array with _token: "esOKmY8Tpr4UvhTYMhWcWui0rpvYEjJ3es7ggics"
jQuery.ajax({
type: "POST",
url: '/my-route',
data: data,
success: function() {
console.log("A");
}
});
The data which I want to post are little chunk of a bigger form, and with using this approach, I can autocomplete form. The little chunk of html inputs are not inside any other sub-form. Maybe this can be the case?
- Form:
- A: bla // to be posted
- B: hello // to be posted
- C: smt else // no post
but getting the values are working okay
Route:
Route::post('/my-route', 'AdminController#theFunction')->middleware('admin');
Edit: I changed <input> to <meta> tag
I had the same problem
try to put include CSRF tag in your meta like so
<meta name="csrf-token" content="{{ csrf_token() }}" />
and read it in your ajax code like so :
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
Last Update
Please modify your url variable like so :
jQuery.ajax({
type: "POST",
url: '/my-route'+'?_token=' + '{{ csrf_token() }}',
data: data,
success: function() {
console.log("A");
}
});
Try This
var formData = new FormData();
formData.append("_token", "{{ csrf_token() }}");
$.ajax({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
},
url: 'save_search',
data: formData,
processData: false,
type: 'POST',
success: function ( data ) {
alert( data );
}
});

unable to retrieve data sent via ajax in controller Laravel 5.1

I am sending data via ajax to my controller as
$.ajax({
url: 'test',
type: 'POST',
data: { id: sessionStorage.getItem('user_id') },
dataType: 'json',
contentType: "application/json; charset=utf-8"/*,
success:function(id){
alert(sessionStorage.getItem('user_id'));
}*/
});
and in the controller I am using
public function getUserMessages(){
$id = Input::get('id');
$messages = Message::where('message_by' , Auth::user()->id)->where('message_for',$id)->get();
echo "id is ",$id;
return $messages;
}
I am getting nothing in $id. I have also tried $_POST['id'] which says undefined index id. How I can retrive the id value?
$request->has('id') returns false too.
You should use the Request class instead of Input:
public function getUserMessages(\Illuminate\Http\Request $request){
$id = $request->id;
$messages = Message::where('message_by' , Auth::user()->id)->where('message_for',$id)->get();
return $messages;
}
Your ajax call doesn't work and will throw a 500 Server Error because you need to pass laravel's csrf token with it whenever you POST something. Create a meta tag at the top of your blade view like:
<meta name="_token_" content="{{ csrf_token() }}">
and get the value when you are doing the ajax call:
$.ajax({
url: '/test',
type: 'POST',
data: {
id: sessionStorage.getItem('user_id'),
_token:document.getElementsByName('_token_')[0].getAttribute('content')
},
success:function(id){
alert(id);
}
});
Most likely the success function in your ajax call will only alert [object Object], to get a better overview over whats returned, use
console.log(id);
instead.
You may also create an error function for the ajax call so that possible errors will be shown. Just do add
error: function(err){
console.log(err);
}
after the success function.
The problem is that you are setting the application content as json, You don't need to set the content.
jQuery ajax
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
$.ajax({
url: 'test',
type: 'POST',
data: { id: sessionStorage.getItem('user_id') },
dataType: 'json',
success:function(data){
console.log(data); // always good to output content for debugginn
}
});
Hope this help. Your ajax should work now.
Have you a route for AJAX requests? (I don't see it.)
Please try following code:
In your AJAX code:
$.ajax({
type: "POST",
url: "{{ route('ajax_route') }}",
data: { _token: "{{ csrf_token() }}", data: "sample data" },
success: function(data){
$(".result").html(data);
},
dataType: "json"
});
In your controller code:
public function ajaxAction(Request $request){
if ($request->isXmlHttpRequest() && $request->isMethod('post')) {
$data = $request->input('data', null);
echo json_encode($data);
}
}
In your route code:
Route::post('/ajax_route', ['as' => 'ajax-action', 'uses' => 'YourController#ajaxAction']);

When sending jQuery post to MVC controller getting 404 error

I'm sending from view using jQuery to MVC post action
function DoSomething(passedId) {
$.ajax({
method: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
//
});
}
And inside MyController
[HttpPost]
public ActionResult SomeAction(int id)
{
...
}
In Firebug console I'm getting 404 error.
You didn't said which version of jquery you are using. Please check jquery version and in case that this version is < 1.9.0 you should instead of
method: "POST"
use
type: "POST"
this is an alias for method, and according to jquery official documentation you should use type if you're using versions of jQuery prior to 1.9.0.
function DoSomething(passedId) {
$.ajax({
type: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
...
});
}
Tested above code and it works (each request enter inside mvc controller http post SomeAction action).
In the RFC 2616 the code 404 indicates that the server has not found anything matching the Request-URI.
So you need to look at your URL parameter.
Try the MVC conventional call using :
url: '#Url.Action("SomeAction", "MyController")',
To resolve the 404 issue:
There are a few options to resolve this. You controller/action cannot be find the way it is describe.
-If you are in a view that is in the controller for which the action your are trying to call is located, then:
url: 'SomeAction',
-If you are trying to call an action from another controller, OtherController, for example, then:
url: 'Other/SomeAction',
-To add to another answer, if you are calling your ajax inside the view (and NOT in a javascript file) then you can also use (for a controller called SomeController):
url: '#Url.Action("SomeAction", "Some")',
Additional Items Of Note:
You do not specify a content type for json (contentType indicates what you are sending):
contentType: "application/json; charset=utf-8",
I can't tell, based on your action if you are expecting 'text' or something else. However, unless expecting 'json', I would remove the data part.
You need to stringify your data
JSON.stringify(data: { id: passedId}),
In the end, I would expect it to look something like:
function DoSomething(passedId) {
var url = "SomeAction"; //if action is in OtherController then: "Other/SomeAction"
$.ajax({
method: "POST",
url: url,
data: JSON.stringify({ id: passedId}),
contentType: "application/json; charset=utf-8"
}).done(function (data) {
//
});
}
The slash at the beginning of this designates an absolute path, not a relative one.
/MyController/SomeAction/
You should include a URL or relative path.. maybe
'MyController/SomeAction/ajax.php'
or the full URL
'http://example.com/myajaxcontroller/someaction/ajax.php'
or stolen from the other guys answer
url: '#Url.Action("SomeAction", "MyController")',
To address others on here, I don't think the datatype is the
problem... OP says "I'm getting 404 error."
contentType is the type of data you're sending, so
application/json; charset=utf-8 is a common one, as is
application/x-www-form-urlencoded; charset=UTF-8, which is the
default.
dataType is what you're expecting back from the server: json, html,
text, etc. jQuery will use this to figure out how to populate the success function's parameter.
Write the code this way:
function DoSomething(passedId) {
$.ajax({
url: 'yourController/SomeAction',
type: 'POST',
data: { id: passedId},
dataType: 'json',
error: function (ex) {alert(ex.responseText)},
success: function (data)
{
if (data.Results != null) {
//use the return values
});
}
}
});
}
and the controller
public JsonResult SomeAction(int id)
{
try
{
return Json(new { Results = "Text To return or send some object or an list, etc"}, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
Finally, check that the controller has its respective view. :)
and and the library of "jQuery" updated.
just in case.
use the following ajax call
var datum = { id: passedId };
$.ajax({
url: url, // your url
type: 'POST',
data: JSON.stringify(datum),
contentType: 'application/json; charset=utf-8',
beforeSend: function () {
},
complete: function () {
},
success: function (user, status, XHR) {
},
error: function (req, status, error) {
}
});
UpDated
public ActionResult SomeAction(int id){} should accept string parameter instead of int

Categories

Resources