I have a problem with updating data in Laravel 5.5. When I am trying to update record of resource controller, I am getting MethodNotAllowedException, but I am using PUT method. Here are details:
Routes:
Route::middleware(['auth'])->group(function(){
Route::get('/', 'DashboardController#index')->name('home')
Route::resource('stages', 'StagesController');
});
Form:
Ajax method:
$('#ajax_form_modal').on('submit', 'form', function (event) {
event.preventDefault();
var $modal = $('#ajax_form_modal');
var $modal_dialog = $modal.find('.modal-dialog');
var $form = $(this);
var method = 'post';
if ($form.find('[name="_method"]')) {
method = $form.find('[name="_method"]').val(); //this fires
} else if ($form.has('method')) {
method = $form.attr('method');
}
//method = 'PUT'
$.ajax({
url: $(this).attr('href'),
dataType: 'json',
type: method,
data: $(this).serialize(),
Response:
"trace": [
{
"file": "\\vendor\\laravel\\framework\\src\\Illuminate\\Routing\\RouteCollection.php",
"line": 238,
"function": "methodNotAllowed",
"class": "Illuminate\\Routing\\RouteCollection",
"type": "->",
"args": [
[
"GET",
"HEAD",
"POST"
]
]
},
Route:List:
I have no idea, why update method allows only 'GET','HEAD','POST', i tried to handle update manually using Post method and it works, also tried to debug place where route mismatch happens but no luck. Can anyone advise something? I really don't want to broke RESTFUL of my controllers.
I find out the bug: href should be action, need more sleep...
$.ajax({
url: $(this).attr('href'),
dataType: 'json',
type: method,
data: $(this).serialize(),
Related
I use this call: https://{site_url}/_api/web/GetFolderByServerRelativeUrl('/ Folder Name')/Files/add(url ='a.txt', overwrite = true).The file is inserted correctly but I don't know what to add so that I can fill the rest of the columns of the library of documents.But it can be done in the same call, it doesn't matter. But I need to modify the value in a record of a document library
Warrior,
Do you want to update values of other columns after uploading a file to a library? If so, you may hava a look below demo:
function getItem(file) {
var call = jQuery.ajax({
url: file.ListItemAllFields.__deferred.uri,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
return call;
}
function updateItemFields(item) {
var now = new Date();
var call = jQuery.ajax({
url: _spPageContextInfo.webAbsoluteUrl +
"/_api/Web/Lists/getByTitle('Documents')/Items(" +
item.Id + ")",
type: "POST",
data: JSON.stringify({
"__metadata": { type: "SP.Data.DocumentsItem" },
CoordinatorId: _spPageContextInfo.userId,
Year: now.getFullYear()
}),
headers: {
Accept: "application/json;odata=verbose",
"Content-Type": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
"IF-MATCH": item.__metadata.etag,
"X-Http-Method": "MERGE"
}
});
return call;
}
You need to put this operation in a separated request.
BR
I am trying to upload a file through a form submit using Ext.Direct, however Ext.direct is sending my request as type 'application/json' instead of 'multipart/form-data'
Here is my form.
{
xtype: 'form',
api: {
submit: 'App.api.RemoteModel.Site_Supplicant_readCSV'
},
items: [
{
xtype: 'filefield',
buttonOnly: false,
allowBlank: true,
buttonText: 'Import CSV'
}
],
buttons:
[
{
text: 'Upload',
handler: function(){
var form = this.up('form').getForm();
if(form.isValid()){
form.submit({
waitMsg: 'Uploading...',
success: function(form, action){
console.log(action.result);
}
});
}
}
}
]
},
On the HTTP request, it checks to see if the request options is a form upload.
if (me.isFormUpload(options)) {
which arrives here
isFormUpload: function(options) {
var form = this.getForm(options);
if (form) {
return (options.isUpload || (/multipart\/form-data/i).test(form.getAttribute('enctype')));
}
return false;
},
getForm: function(options) {
var form = options.form || null;
if (form) {
form = Ext.getDom(form);
}
return form;
},
However, options looks like this
{
callback: function (options, success, response) {
jsonData: Object
action: "RemoteModel"
data: Array[1]
0: form
length: 1
__proto__: Array[0]
method: "Site_Supplicant_readCSV"
tid: 36
type: "rpc"
__proto__: Object
scope: constructor
timeout: undefined
transaction: constructor
}
And there is no direct form config, but it exists in jsonData.data[0]. So it doesn't set it as type multipart/form-data and it gets sent off as type application/json.
What am I doing wrong? Why isn't the form getting submitted properly?
Edit - I am seeing a lot of discussion about a 'formHandler' config for Ext.Direct? I am being led to assume this config could solve my issue. However I don't know where this should exist. I'll update my post if I can find the solution.
Solution - Simply adding /formHandler/ to the end of the params set the flag and solved my issue. Baffled.
Supplicant.prototype.readCSV = function(params,callback, request, response, sessionID/*formHandler*/)
{
var files = request.files;
console.log(files);
};
The method that handles file upload requests should be marked as formHandler in the
Ext.Direct API provided by the server side.
EDIT: You are using App.api.RemoteModel.Site_Supplicant_readCSV method to upload files; this method needs to be a formHandler.
I'm not very familiar with Node.js stack but looking at this example suggests that you may need to add /*formHandler*/ descriptor to the function's declaration on the server side.
I have resource that has following fields:
description, picture
Is it possible to send that resource to URL as multipart/form, and if so, how?
I've tried putting:
app.factory('resource_name', ['$resource', function($resource) {
return $resource('<url> ',
{
<params_for_url>
},
save: {
method: "POST",
headers: {
"Content-Type": "multipart/form-data;"
}
},
but this doesn't get to the server as form-data. It goes like JSON with header just set:
{
description: "gtrdgf",
picture: {
lastModifiedDate:2013-11-26T20:42:13.000Z,
name: "suggested_pokes.png"
size: 32995
type: "image/png"
webkitRelativePath: ""
}
Did anyone met this requirement before? If this is possible at all...
Thanks!
I found solution for this one. You have to use FormData to submit it. You can use it as interceptor. I used it like this (this is my save method of ngResource)
save: {
method: 'POST',
transformRequest: formDataObject,
headers: {'Content-Type':undefined, enctype:'multipart/form-data'}
},
and here is transformer:
function formDataObject (data) {
var fd = new FormData();
angular.forEach(data, function(value, key) {
fd.append(key, value);
});
return fd;
}
how come when i'm clicking on the update button popup kendo grid , this error ocurrs?
The error in Firefox browser is in this form : SyntaxError: missing ; before d.0=value
and in Chrome browser : Uncaught SyntaxError: Unexpected number
I've uploaded a video regarding this error for elaboration n stuff
Jsfiddle Code
Video
Code
transport: {
read: {
url: 'https://dl.dropboxusercontent.com/sh/u9oxg5f6uweqh40/CbR3pNVg04/documentj',
dataType: 'json',
type: 'get',
cache: false
},
update: function(e) { return true; }
}
save: function (e) {
var that = this;
$.ajax({
url: '/echo/json',
type: e.model.id == null ? 'POST' : 'PUT',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(e.model),
success: function (data) {
// Alertify.log.success(data);
console.log('ok dadasaved');
that.refresh();
},
error: function (data) {
// Alertify.log.error(data);
console.log('no datasaved');
that.cancelRow();
}
});
}
You should provide more code to detect what's wrong with your code, but read this may help you:
Such error occurs when the transport definitions are inconsistent. In other words, if you would like to use custom transport method, all transport types should be defined as functions.
Having a standard read transport and custom update is not supported. Please configure all transports as functions and let me know if the error still occurs.
I had the same error and for me the problem was that the dataType option was not set for all transport methods. I marked that line with a comment below:
var linksDataSource = new kendo.data.DataSource({
transport: {
read: {
dataType: "json",
url: 'read-url',
type: "get"
},
destroy: {
dataType: "json", /* <============ THIS LINE WAS MISSING */
url: 'delete-url',
type: "delete"
},
update: {
dataType: "json",
url: 'update-url',
type: "post"
},
create: {
dataType: "json",
url: 'create-url',
type: "post",
complete: function () {
$("#searchResult").data("kendoGrid").dataSource.read();
}
},
/* ... */
I'm trying to convert a REST call using Cordova plugin to a JQuery AJAX POST. I don't have the JQuery code right, the call is getting a connection refused error (hitting localhost). I'm successfully making GET requests to my localhost, so there isn't a connectivity issue.
The REST API code:
#Path("/track")
public class TrackResource {
...
The method in TrackResource class i'm trying to hit :
#POST
#Path("{trackid}")
#Consumes("application/json")
#Produces("application/json")
public Response addToResource(#PathParam("trackid") String trackid, String bodyJson) {
The AJAX code:
var trackingJSON = JSON.stringify(tracking_data);
var urlAjax = "http://localhost:7001/ds/resources/track/" + trackid;
$.ajax({
type: "POST",
url: urlAjax,
data: trackingJSON,
beforeSend: function() { $.mobile.showPageLoadingMsg("b", "Loading...", true) },
complete: function() { $.mobile.hidePageLoadingMsg() },
success: function(data) { alert("ajax worked"); },
error: function(data) {alert("ajax error"); },
dataType: 'json'
});
I'm not sure if i'm using the data option in the ajax call correctly, but it's my understanding that is where you would put the data you want to pass server side.
I do have other GET calls to this same TrackResource class working, so i know the base part of the URL is correct. I know the trackid value is populated correctly as well.
If you're posting a JSON string make sure you also set contentType: "application/json".
var trackingJSON = JSON.stringify(tracking_data);
var urlAjax = "http://localhost:7001/ds/resources/track/" + trackid;
$.ajax({
type: "POST",
url: urlAjax,
contentType: "application/json",
data: trackingJSON,
beforeSend: function() { $.mobile.showPageLoadingMsg("b", "Loading...", true) },
complete: function() { $.mobile.hidePageLoadingMsg() },
success: function(data) { alert("ajax worked"); },
error: function(data) {alert("ajax error"); },
dataType: 'json'
});
I needed to use the router address of my computer, 192...., in order to hit my localhost... I was running the application on an actual Android device, however, I guess trying to use localhost or 127.0.0.1 in the AJAX call must have been causing issues.