I am trying to put to a method in a controller using ajax but I keep getting a 404 not found.
My JS:
var dataroomForm = $('#dataroomForm');
var dataroomId = $('#dataroomId').val();
var saveButton = $('.saveDataroom');
saveButton.click(function(e) {
var dataroomData = dataroomForm.serialize();
e.preventDefault();
console.log(dataroomData);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/dataroom/' + dataroomId,
type: 'PUT',
data: {
'dataroom': dataroomData
},
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (request, error) {
alert("Request: " + JSON.stringify(request));
}
});
});
The route I am trying to trigger:
Route::put('dataroom/{dataroom}', ['as' => 'update', 'uses' => 'DataroomController#update']);
And update method (not really relevant I think but posting for complete view)
public function update(DataroomRequest $request, $id, MailService $mailService)
{
$dataroom = Dataroom::withoutGlobalScope(ActiveScope::class)->find($id);
if (is_null($dataroom)) {
\Flash::error('Dataroom niet gevonden!');
return redirect(route('admin.dataroom.index'));
}
$dataroom->fill($request->all());
$dataroom->save();
$dataroom->handleUploader($request, 'image');
if ($request->has('send_update')) {
$changes = $request->input('changes');
foreach ($dataroom->accounts as $account) {
$mailService->sendUpdate($account, $dataroom, $changes);
}
if (empty($changes)) {
$changes = 'Dataroom gewijzigd';
}
$dataroom->log($changes);
}
\Flash::success('De wijzigingen voor <strong>' . $dataroom->title . '</strong> zijn opgeslagen');
return redirect()->route('admin.dataroom.index');
}
In my network tab I get:
Request URL: http://website.nl.test/dataroom/26
Request Method: PUT
Status Code: 404 Not Found
And as response : exception: "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException"
What am I doing wrong?
I don't see any issues in your code try using the command in your terminal php artisan optimize:clear in root folder this will flush/remove the application cache, route cache, and config cache altogether.
Related
I have an issue with a simple jQuery $.post in my application. I have tried many methods and solutions on the internet to no avail. When post request is sent I see 400 error
public class RecoveryAdhocInvoicingModel : PageModel
{
Public IActionResult OnPostDoJob(string invNo, string account)
{
//var emailAddress = Request.Form["emailaddress"];
// do something with emailAddress
return new JsonResult("");
}
}
In my script the $.post method is called via button click:
$('#submitBtnUpdateJob').click(function (evt) {
var formdata = new FormData();
formdata.append("invNo", $('#adhocInvoiceNumber').val());
formdata.append("account", $('#invoiceAccountInput').val());
$.post(window.location.href + '?handler=DoJob', JSON.stringify(formdata), function () {
alert('Posted');
});
});
Solution folder path
You need to add the RequestVerificationToken header to the request.
$.ajax({
type: "POST",
headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
url: window.location.href + '?handler=DoJob',
data: {
"invNo": $('#adhocInvoiceNumber').val(),
"account": $('#invoiceAccountInput').val()
},
contentType: "application/x-www-form-urlencoded"
}).done(function (response) {
alert('Posted');
});
Documentation: https://www.learnrazorpages.com/security/request-verification#ajax-post-requests-and-json
I want to create an upload adapter for ckeditor,
I have an issue in my laravel ajax application,
here is my code.
export default class UploadAdapter {
constructor(loader) {
this.loader = loader;
}
upload() {
return new Promise((resolve, reject) => {
let data = new FormData();
data.append('upload', this.loader.file);
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/loadImage',
type: 'POST',
data: data,
dataType: 'json',
async:false,
processData: false,
contentType: false,
success: function (data) {
console.log(data.get('upload'));
},
error: function (request, status, error) {
console.log(error);
}
});
});
}
}
I stuck in responding with ajax to laravel controller.
Here is my Controller function:
try {
$file = $request->file('upload');
$uploader = MediaUploader::fromSource($file);
$uploader->setAllowedMimeTypes(['image/jpeg', 'image/gif', 'image/png']);
$uploader->setAllowedExtensions(['jpg', 'jpeg', 'png', 'gif']);
$media = $uploader->upload();
return response()->json([
'uploaded' => true,
'url' => $media->getUrl()
]);
} catch (\Exception $e) {
return response()->json(
[
'uploaded' => false,
'error' => [
'message' => $e->getMessage()
]
]
);
}
Here is my error
SyntaxError: Unexpected end of JSON input
at parse (<anonymous>)
at ajaxConvert (app.js:11826)
at done (app.js:12294)
at XMLHttpRequest.<anonymous> (app.js:12587)
What is the error in my code ???
I cant get the file information in laravel controller..
How can i solve this issue...? Help me Please!!!
You have data - empty
JSON.parse(''); // SyntaxError: Unexpected end of input
Add verification:
data = data != "" ? $.parseJSON(data) : {};
I am trying to run an Ajax post call through my entire application, it shall update the Navigation. On some pages it works but on others it does not, how can I fix this and make it global so to say.
I am using Laravel as a php Framework.
# Middleware group if user is logged in
Route::group(['middleware' => 'auth'], function () {
# Notifications
Route::group(['prefix' => 'notification', 'as' => 'notification.'], function () {
Route::post('number', ['as' => 'number', 'uses' => 'NotificationController#number']);
});
Route::group(['prefix' => 'relation', 'as' => 'relation.'], function () {
Route::get('show/{id}', ['as' => 'show', 'uses' => 'RelationController#show']);
});
});
in my layouts/app.blade.php I include the js file like this
<script src="{{ asset('js/liveUpdater.js') }}"></script>
#yield('javascript')
the liveUpdater ajax function
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
}
});
$.ajax({
url: 'number',
type: 'post',
success: function(data) {
$('#number-of-notifications').text(data.unread);
},
error: function(data) {
console.log('error number ' + data.data);
}
});
The Url http://localhost/myApp/public/notification/all returns a success message.
But an url for example like this http://localhost/myApp/public/relation/show/1 Returns an error message:
number
/myApp/public/relation/show
405
Method Not Allowed
You are prefixing the route with notification so your ajax request should point to notification/number:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
}
});
$.ajax({
url: 'notification/number',
type: 'post',
success: function(data) {
$('#number-of-notifications').text(data.unread);
},
error: function(data) {
console.log('error number ' + data.data);
}
});
Also I think aliasing (in the group) wouldn't help, so I think (for simplicity) you could have:
Route::group(['middleware' => 'auth'], function () {
# Notifications
Route::group(['prefix' => 'notification'], function () {
Route::post('number', 'NotificationController#number']);
});
});
Routing groups docs
You've to define route path and corresponding controller methods for every url paths like for relation/show and notification/all :
Route::group(['middleware' => 'auth'], function () {
# Notifications
Route::group(['prefix' => 'notification'], function () {
Route::post('show/{show}', 'NotificationController#show']);
Route::post('number', 'NotificationController#number']);
Route::post('all ', 'NotificationController#all']);
});
});
mistake in your request method in ajax. it should be type: "GET", OR in your web.php like Route::post('show/{id}' instead of Route::get('show/{id}'
your request method is not matching that why its throwing 405
AJAX:
$(document).ready(function () {
$('.my_button').click(function () {
var data = $(this).val();
//alert(BASE_URL);
$.ajax({
type: "POST",
ContentType: 'application/json',
data: data,
url: BASE_URL + 'index.php?deo/dashboard',
error: function () {
alert("An error occoured!");
},
success: function (msg) {
alert('result from controller');
}
});
alert(data);
});
});
CONTROLLER:
public function dashboard() {
$data = $this->input->post('data');
$data = json_decode($data);
echo "<script>alert('count ".$data."');</script>";
}
Am trying to send value from my jquery, ajax to controller, am able to get value from my view page to jquery page and able to print that. But unable to send the value from ajax page to controller page, after sending the data i got the success data. but unable to get and print the data in my controller page. Thanks in advance
If your using firefox a good thing to use is firebug add on and then you can use the console to check for errors on there. To see if the ajax has any errors while sending.
Remove question mark after index.php? and I think your base url is not working correct try just.
Url
// With index.php
url: 'index.php/deo/dashboard',
// Or without index.php
url: 'deo/dashboard',
Or
// With index.php
url: <?php echo site_url('index.php/deo/dashboard');?>,
// Or without index.php
url: <?php echo site_url('deo/dashboard');?>,
Script
$(document).ready(function () {
$('.my_button').click(function () {
var data = $(this).val();
$.ajax({
type: "POST",
data: data,
url: 'index.php/deo/dashboard',
// url: <?php echo site_url('index.php/deo/dashboard');?>,
success: function (msg) {
alert('result from controller');
},
error: function () {
alert("An error occoured!");
}
});
alert(data);
});
});
Controller
public function dashboard() {
$data = $this->input->post('data');
echo "<script>alert('count ".$data."');</script>";
}
I am now trying to build a dnn module using ajax calls. But there is a jquery error stating
SyntaxError: Unexpected token <
I have tried to work around with ajax "url: " and tried to create a new ascx at the root folder but still showing error 404.
My ajax call is as below
$.ajax({
url: "NewsManagement.ascx/Add",
contentType: "application/json; charset=utf-8",
dataType: "json",
method: "POST",
beforeSend: function () {
},
cache: false,
data: {
title : $('#txt_Title').val(),
news_content : $('#txt_Content').val(),
image : $('#file_Image').val(),
chapter_id : $('#sel_Chapter').val(),
is_draft : $('#chk_Draft').val(),
posted_date : $('#dp_PostDate').val(),
created_by : "",
lastupdate_by : ""
},
success: function (data) {
console.log(data);
if (data == "success") {
console.log(data);
}
else {
initMdlError("SERVER : " + data);
}
},
error: function (data, textStatus, error) {
// ERROR IS BEING CALLED FROM HERE
console.log("JQUERY JAVASCRIPT : " + error);
initMdlError(error);
},
complete: function () {
console.log('complete');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Is there any way to solve the issues?
The problem you're running into is that DNN isn't handling the requested URL properly that you are calling. If you want to call a service URL in DNN you're going to want to setup routes to handle the calls.
namespace Christoc.Com.Modules.SlidePresentation.services
{
public class SlidePresentationRouteMapper : IServiceRouteMapper
{
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapRoute("SlidePresentation", "{controller}.ashx/{action}",
new[] {"Christoc.Com.Modules.SlidePresentation.services"});
}
}
}
In the Controller you can define the methods available
[DnnAuthorize(AllowAnonymous = true)]
public ActionResult ListOfSlides()
{
try
{
var slides = Slide.GetSlides(ActiveModule.TabID, ActiveModule.ModuleID);
return Json(slides, JsonRequestBehavior.AllowGet);
}
catch (Exception exc)
{
DnnLog.Error(exc);
return Json(null, JsonRequestBehavior.AllowGet);
}
}
https://slidepresentation.codeplex.com/SourceControl/latest#DesktopModules/SlidePresentation/services/SlidePresentationController.cs
sample Javascript
//get slides on initialization
this.init = function(element) {
//var data = {}; //removed because we don't need this
//data.moduleId = moduleId; //removed because we don't need this when calling setModuleHeaders
//data.tabId = tabId; //removed because we don't need this
//serviceFramework.getAntiForgeryProperty(); //removed because we don't need this
$.ajax({
type: "POST",
cache: false,
url: baseServicePath + 'ListOfSlides',
//data: data,
//dataType:"json",
beforeSend: serviceFramework.setModuleHeaders
}).done(function(data) {
viewModel.slides = ko.utils.arrayMap(data, function(s) {
return new slide(s);
});
ko.applyBindings(viewModel);
$(element).jmpress();
}).fail(function () {
Console.Log('Sorry failed to load Slides');
});
};
Here's an example module that does this
https://slidepresentation.codeplex.com/
And a user group video I did years ago on this module.
https://www.youtube.com/watch?v=hBqn5TsLUxA