I'm trying to drop and resize an event in fullcalendar in laravel, but when I move the event, I have 405 Method Not Allowed error message!..
My web.php file:
Route::get('calendar', 'FullCalendarController#index');
Route::get('/load-events', 'EventController#loadEvents')->name('routeLoadEvents');
Route::put('/events-update', 'EventController#update')->name('routeEventUpdate');
My blade.php file:
<div id='calendar'
data-route-load-events="{{route('routeLoadEvents')}}"
data-route-events-update="{{route('routeEventUpdate')}}"></div>
My .js file:
$(function (){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
function sendEvent(route, data_){
$.ajax({
url: route,
data: data_,
method: 'POST',
dataType: 'json',
success: function(json){
if(json){
location.reload();
}
}
});
}
function routeEvents(route){
return document.getElementById('calendar').dataset[route];
}
eventDrop: function(element){
let start = moment( element.event.start ).format("YYYY-MM-DD HH:mm:ss");
let end = moment( element.event.end ).format("YYYY-MM-DD HH:mm:ss");
let newEvent = {
_method: 'PUT',
id: element.event.id,
start: start,
end: end
};
sendEvent(routeEvents('routeEventUpdate'), newEvent);
},
So there are really only two types of request that Laravel really understands:
POST & GET
A PUT request is a POST request with a method of PUT.
What laravel is looking for is a _method parameter in the request telling it what type of request this is. in your case _method: PUT.
Try this:
$.ajax({
url: route,
data: data_,
method: 'PUT',
dataType: 'json',
success: function(json){
if(json){
location.reload();
}
}
});
You put your "put" method in your payload-data, this wont be recocnized by the AJAX Function. Try adding the method as an Argument
function sendEvent(route, data_, sendMethod){
...
method: sendMethod,
...
And call i via
sendEvent(routeEvents('routeEventUpdate'), newEvent, 'PUT');
Related
Want to Access Show function data through AJAX, but it returns error when i passed id variable in route
Contoller
public function show($id)
{
$features['UnitFeatures'] = UnitFeatures::find($id);
return $features;
}
View Blade File
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var feature_id = $('#unitFeatures').val();
$.ajax({
url: '{{ route('unitfeatures.show',feature_id) }}', // error in this line when i pass feature_id value to route
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
Please give me a solution
The problem is that you cannot access a JS variable in your {{}} PHP code.
You will have to get the route uri and replace the placeholder manually in your JS code.
You can get the URI of your Route with this piece of code:
\Route::getRoutes()->getByName('unitfeatures.show ')->uri
This returns the uri as a string like that: /sometext/{id}
Now you can simply replace the {id} with the feature_id by using str.replace() or whatever function you like.
var feature_id = $('#unitFeatures').val();
var origUrl = '{{ \Route::getRoutes()->getByName('unitfeatures.show ')->uri}}';
$.ajax({
url: origUrl.replace('{id}', feature_id),
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
Problem With You are using Javascript Variable in PHP Code You can use Javascript Variable After Execution of PHP Code treated as a String.
$.ajax({
url: "{{ route('unitfeatures.show') }}"+'/'+feature_id,
type: 'GET',
dataType: 'json',
success: function(response){
console.log(response);
}
});
});
I'm trying to send data with ajax t controller and i get 405 error
Code
JS
$(document).ready(function(){
$('body').on('click', '.addbundlebutton', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
e.preventDefault();
var data= [];
$("input:checkbox[name=bundleProducts]:checked").each(function(){
data.push($(this).val());
});
// data are like ['41', '46'] in console //
$.ajax({
type: "post",
url: "{{ url('testadd-bundle') }}",
data: JSON.stringify(data),
success: function (data) {
console.log(data.success);
$(".addbundlebutton").remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
Route
Route::post('/add-bundle', 'frontend\BundleController#add');
Controller
public function add(Request $request){
//testing data...
$data = $request->all();
return response()->json($data);
}
Screenshot
Any idea?
You use this URL: url: "{{ url('testadd-bundle') }}",
But your route is set to be:
url('/add-bundle')
So try that instead. 405 means method not allowed, which means you try post on a get route for example.
I m getting Internal server error (500) making an AJAX request. I m not sure why the request is failing. Need help in this. Here is my code.
$('#LanguageId').on('change', function(){
var setValue =JSON.stringify( $('#LanguageId').val());
console.log(typeof(setValue));
$.ajax({
url: '/RootObjects/SaveLanguage',
type: 'POST',
dataType: 'json',
data:setValue ,
contentType: 'application/json; charset=utf-8',
success: function (data) {
}
});
})
and the controller's action
[HttpPost]
public ActionResult SaveLanguage(string LanguageId)
{
GlobalVariables.LangId = LanguageId.ToString();
return View("Index");
}
can't understand what is wrong
Change your ajax request like this:-
$('#LanguageId').on('change', function(){
var setValue =$('#LanguageId').val();
console.log(typeof(setValue));
$.ajax({
url: '/RootObjects/SaveLanguage',
type: 'POST',
dataType: 'json',
data:{'LanguageId':setValue} ,
success: function (data) {
}
});
})
I want to use jQuery POST method to call an xsjs service that does some modifications in Database.My xsaccess file prevents xsrf, so I need to handle it in my controller method.
Below is my controller code-
var obj= {};
obj.name= "John";
obj.age= "abc#xyz.com";
obj.loc= "Minnesota";
jQuery.ajax({
url: "serviceTest.xsjs",
type: "GET",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
success: function(responseToken, textStatus, XMLHttpRequest) {
var token = XMLHttpRequest.getResponseHeader('X-CSRF-Token');
console.log("token = " +token);
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", token);
},
success : function(response) {
// will be called once the xsjs file sends a
response
console.log(response);
},
error : function(e) {
// will be called in case of any errors:
var errMsg = e.responseText
console.log(e);
}
});
},
And here is my xsjs code-
var csrf_token = $.request.headers.get("X-CSRF-Token");
if(csrf_token === "Fetch") {
var content = $.request.body.asString();
var args = $.parseJSON(content);
var xsName= args.name;
var xsemail= args.email;
var xsLoc= args.loc;
//then execute DML statement by passing these 3 parameters as arguments.
catch (error) {
$.response.setBody(content);
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
I am not able to do the update and getting error Err 500 - Internal server Error.
Any suggestions would be extremely helpful
Edit:
If I forgot the token then I got a 403 Access denied error ("CSRF token validation failed") and not a 500 internal. So I think something is wrong with your services
You can add your X-CSRF-Token as header of your POST request with setup your ajax requests before your fire your POST.
$.ajaxSetup({
headers: {
'X-CSRF-Token': token
}
});
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
Otherwise add it to each POST request.
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
headers: {
'X-CSRF-Token': token
},
beforeSend: function(xhr) {
Your way with using beforeSend event should work too.
I am having trouble getting an ajax GET request (or any request for that matter) to retrieve the response. I am simply trying to return the response in an alert event:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXX&scope=crmapi&criteria=(((Potential Email:test#email.com))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: function(data) {
alert(data);
}
});
});
});
</script>
I can get this and other similar post requests to work by taking away the function in the success option and editing the code like this:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=XXXX&scope=crmapi&criteria=(((Potential Email:test#email.com))&selectColumns=Potentials(Potential Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: alert('success')
});
});
});
</script>
Why is this? And more importantly, how can I retrieve the response data and transfer it to an alert message? Any help is appreciated!
** Update:
Upon reading the first two users' responses on this question, this is what I have:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'GET',
url: 'https://crm.zoho.com/crm/private/json/Potentials/searchRecords?authtoken=418431ea64141079860d96c85ee41916&scope=crmapi&criteria=(((Potential%20Email:test#email.com))&selectColumns=Potentials(Potential%20Name)&fromIndex=1&toIndex=1',
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function(data) {
alert(JSON.stringify(data));
}
});
});
});
</script>
I am able to get the error response, so I can confirm there is some kind of error. I also want to point out that I am making the request from a different domain (not crm.zoho.com) so should I be using jsonp? If so, how would I alter the code?
When you have
success: alert('success')
you do NOT have a successful request, you are actually executing this function at the start of AJAX method. The success parameter requires a pointer to a function, and when you use alert('success') you are executing a function instead of providing a pointer to it.
First thing that you need to try is to update type to GET instead of Get:
$.ajax ({
type: 'GET',
Try using the .done() function as follows:
<script>
$(document).ready(function() {
$('#test').click(function() {
$.ajax ({
type: 'Get',
url: 'yourUrl',
dataType: 'json',
}
}).done(function(result) {alert(data);}) //try adding:
.error(function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);})
});
});
the error function will also give you some information in your console as to the status of your request.