I try to make POST-request to method of admin controller using AJAX (from admin part). My JS code:
<script>
$(".remove-request-btn").on('click', function () {
let request_id = $(this).data('request-id');
let confirm_result = confirm('Are you sure you want to delete this request?');
if (confirm_result) {
$.ajax({
url: 'index.php?route=extension/x_feedback/settings/removeRequest&token={{ token }}',
method: 'post',
dataType: 'json',
data: {request_id: 11},
success: function(data) {
if (data.status === 'ok') {
location.reload();
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
My method:
public function removeRequest()
{
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode(
[
'status' => 'ok'
]
));
}
I expect json in the response but get following:
I tried to add admin into the url like '/admin/index.php?route=extension/x_feedback/button/feedbackRequest&token={{ token }}'
But it doesn't help. Can you help me please what I'm doing wrong? Thank you!
1-please add bellow code into controller method
$data['token'] = $this->session->data['user_token'];
2- use javascript into .twig file - not external js file.
In OC3 is used user_token instead token
so you must use this url:
url: 'index.php?route=extension/x_feedback/settings/removeRequest&user_token={{ user_token }}',
And do not forget declare user_token in the corresponding controller file:
$data['user_token'] = $this->session->data['user_token'];
Related
I want to call storeProduct controller method in ajax URL.
url: './product_catalog/storeProduct'
How to call a method in this URL?
I want to store product_id and campaign id in the database.
Page not found error occurs.
Route :
Route::get('product_catalog','front\ProductCatalogController#showProductCatalogForm');
Route::post('product_catalog',['as' => 'storeProduct', 'uses' => 'front\ProductCatalogController#storeProduct']);
Ajax :
$(".my_form").submit(function(event) {
event.preventDefault(); //prevent default action
var product_id = $(this).find('#product_id').val();
var campaign_id = $(this).find('#campaign_id').val();
console.log(product_id);
console.log(campaign_id);
$.ajax({
type: "POST",
url: './product_catalog/storeProduct',
data: {
'product_id': product_id,
'campaign_id': campaign_id
},
success: function(data) {
alert(data);
console.log(data);
}
});
});
Controller :
public function showProductCatalogForm()
{
//if($_GET["campaign"]!=="")
$campaign=$_GET["campaign"];
return view('front.product_catalog');
}
public function storeProduct(Request $request)
{
$this->validate($request, $this->rules);
$input=Input::all();
$campaign_product=ProductCatalog::create($input);
return redirect('product_catalog');
}
url: {{ url('/product_catalog/storeProduct') }},
your route should be
Route::get('/product_catalog','front\ProductCatalogController#showProductCatalogForm');
your ajax url should be
type: "POST",
url: '/product_catalog',
Or you can use route(); i recommend dont use url() because any time if you want change urls you will need to change it manually.which is not good for app.urls could be 100 or 1000 to change.it could be dangers.
you should try name route like this
Route::get('/product_catalog','front\ProductCatalogController#showProductCatalogForm')->name('product_catalog');
and your ajax url
type: "POST",
url: {{ route('product_catalog') }},
Why you are adding "." In ./product-catalog !
Just use /product-catalog
Use "." when you want to search for folder or any directory or any file in your project directory or any other folder and you are not sure where the file is
Dont use in url when there is a route for the link
try this if you have wrote javascript inside blade :
$(".my_form").submit(function(event) {
event.preventDefault(); //prevent default action
var product_id = $(this).find('#product_id').val();
var campaign_id = $(this).find('#campaign_id').val();
console.log(product_id);
console.log(campaign_id);
$.ajax({
type: "POST",
url: '{{route('storeProduct')}}',//this is only changes
data: {
'product_id': product_id,
'campaign_id': campaign_id
},
success: function(data) {
alert(data);
console.log(data);
}
});
});
use this without the dot before slash.
url: '/product_catalog/storeProduct',
You could use
url:"{{route('route.name')}}"
and it works for me. You could check it by
console.log("{{route('route.name')}}");
inside your script.
I am working on a Laravel 5.3 solution. I try to call a POST route via AJAX from one of my views to update a set of categories but I get a 404 error everytime I call the route.
Interesting fact: During development I was able to call the route with the JS-code shown below successfully - but since I did some updates to the controller code itself it throws a 404 but no exception.
Here is my controller action:
public function updateTree( Request $request )
{
$data = $request->json()->all();
$result = BlogCategory::rebuildTree($data, false);
if($result > 0) {
return Response::HTTP_OK;
}
return Response::HTTP_NOT_MODIFIED;
}
And here the JS AJAX call:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var updateTree = function (e) {
var list = e.length ? e : $(e.target), output = list.data('output');
console.log(JSON.stringify(list.nestable('serialize')));
$.ajax({
url: '{{ action('BlogCategoryController#updateTree') }}',
type: "POST",
data: JSON.stringify(list.nestable('serialize'))
});
};
$(document).ready(function() {
$('#nestable2').nestable({
group: 1
}).on('change', updateTree);
});
The controller route is bound like that in web.php
Route::post( '/service/blog/categories/updatetree', 'BlogCategoryController#updateTree' );
As you might see, I am using the Laravel NestedSet module from LazyChaser here (https://github.com/lazychaser/laravel-nestedset).
Any input is much appreciated.
Cheers,
Jules
you having opening and closing quotes problem in your ajax url, use like this
$.ajax({
url: '{{ action("BlogCategoryController#updateTree") }}',
type: "POST",
data: JSON.stringify(list.nestable('serialize'))
});
I need to send data via JS to a Laravel controller on a button click. I'm not using any form because the data is being created dynamically.
Every time i try to send the data, i get an Internal Server Error (500), but unable to catch that exception in the controller or the laravel.log file.
Here's what i'm doing:
Route:
Route::post('section/saveContactItems', 'SectionController#saveContactItems');
Controller:
public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... }
JS:
$('button').on("click", function (evt) {
evt.preventDefault();
var items = [];
var id = $("#id").val();
var languageID = $("#languageID").val();
var data = { id: id, type: type, items: JSON.stringify(items), languageID: languageID };
$.ajax({
url: "/section/saveContactItems",
type: "POST",
data: data,
cache: false,
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (response)
{
console.log(response);
}
});
});
What am i doing wrong? How can i accomplish this?
UPDATE: Thanks to #ShaktiPhartiyal's answer (and #Sanchit's help) i was able to solve my issue. In case some else comes into a similar problem, after following #Shakti's answer i wasn't able to access the data in the controller. So, i had to stringify the data before sending it to the server:
data: JSON.stringify(data),
You do not need to use
public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... }
You have to do the following:
public function saveContactItems()
{
$id = Input::get('id');
$type = Input::get('type');
$items = Input::get('items');
$languageID = Input::get('languageID');
}
and yes as #Sanchit Gupta suggested you need to send the CSRF token with the request:
Methods to send CSRF token in AJAX:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
If you use this approach you need to set a meta tag like so:
<meta name="csrf-token" content="{{csrf_token()}}">
or
data: {
"_token": "{{ csrf_token() }}",
"id": id
}
UPDATE
as #Sanchit Gupta pointed out use the Input facade like so:
use Input;
I lately managed to get a simple ajax post to work but can't get any of the data in the controller :
Ajax :
function verify(event) {
var title = event.title;
var start = event.start.format("h:m");
$.ajax({
url: "/admin/timetable/verify",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
contentType: "application/json; charset=utf-8",
data: {type : 'hi',titles : title},
dataType: "json",
success: function(response){
if (response['state']==='0')
toastr.error('Are you the 6 fingered man?'+response['msg']);
if (response['state']==='1')
toastr.info('Are you the 6 fingered man?');
},
error : function(e){
console.log(e.responseText);
}
});
}
Controller :
$d = Request::all();
dd($d);
return response()->json(['state'=>'0','msg'=>$d['titles']],200);
I tried Request all, Input all, Input::json()->all() .. nothing works always null or empty array [] ! I'm just trying to read the data sent from the ajax form !
I faced this lately. The problem (I don't know why) was about Get and POST.
Just transform route to a GET, make the ajax type as GET, and try with a very simple Input::all.
public function verifyClassroom(){
$Data = Input::all();
dd($Data);
}
This is my tested code and it works
function verify(event) {
$.ajax({
url: "/test",
headers: {
'X-CSRF-TOKEN': $('#crsf').val()
},
type: "post",
data: {type : 'hi',titles : "title"},
success: function(data){
alert(data);
},
error : function(e){
console.log(e.responseText);
}
});
}
and in my route closure
Route::post('test', function(\Illuminate\Http\Request $request){
$type = ($request->input('type'));
return $type;//returns type->hi
});
in the php controller you need to have something like this.
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class YourcontrollernameController extends Controller {
public function test(Request $request) {
echo $request->input('type');
echo '/';
echo $request->input('titles');
die;
}
}
you can access the type and title by $request->input('type') and $request->input('titles')
ALso try using get method and
in yourproject/routes/web.phpweb.php
Route::get('/test', 'YourcontrollernameController#test');
I have a new.html.twig,I am using few ajax calls on this page on changes events of drop down.
So I have created a septate js file called new.js and keep my all JavaScript code inside this file, instead to write it on same view file.
But here in this js file I am unable to access the routing path which is call a ajax request. on change event.
===========New.twig.html=====================
include(new.js);
<select><name='a' onchange="setLabel('123')"></select>
============new.js.=============
function setLabel(voucherTypeID) {
queryString = "voucherTypeID=" + voucherTypeID;
$('#loading-image').show();
$.ajax({
type: "POST",
url: "{{path('vouchergeneration_getLedgers')}}", //THIS PATH How TO GET
data: queryString,
cache: "false",
dataType: "html",
success: function (data){
});
So here I am not able to access the URL Path, while it was accessible in twig file before. Please guide me how to fix this. I do not want to use anykind of Bundle for this simple work.. Thanks in advance..
There is very simple bundle for this simple work FOSJsRoutingBundle
Once this bundle is enabled you only need to do
Routing.generate('my_route_to_expose', { id: 10 }); // will result in
/foo/10/bar
Routing.generate('my_route_to_expose', { id: 10, foo: "bar" }); //
will result in /foo/10/bar?foo=bar
$.get(Routing.generate('my_route_to_expose', { id: 10, foo: "bar" }));
// will call /foo/10/bar?foo=bar
Routing.generate('my_route_to_expose_with_defaults'); // will result
in /blog/1
Routing.generate('my_route_to_expose_with_defaults', { id: 2 }); //
will result in /blog/2
Routing.generate('my_route_to_expose_with_defaults', { foo: "bar" });
// will result in /blog/1?foo=bar
Routing.generate('my_route_to_expose_with_defaults', { id: 2, foo:
"bar" }); // will result in /blog/2?foo=bar
EDIT:
Of course you can do it without bundle (which I don't think is a good idea). In that case I would advice set your routes in controller's action and set use it in twig template to set js variable. Something like:
Controller:
public function indexAction()
{
return array('yourRoute' => $router->generate('yourRoutName'));
}
your template:
<script type="text/javascript">
var yourRoute = '{{yourRoute}}';
</script>
your js:
(...)
url: yourRoute,
(...)
If you want to embed an URL and get it with your JS, you could do something like the following:
// HTML/Twig
<html data-my-route="{{ path('vouchergeneration_getLedgers') }}">
...
</html>
Then in your JS:
$.ajax({
type: "POST",
url: $('html').attr('data-my-route'),
data: queryString,
cache: "false",
dataType: "html",
success: function (data){
});
It avoids having global variable, and you can use as many data-attribute as you want.
If you are using fetch then you can get the url of the post by using data.url:
fetch('/check', {
method: 'POST', // or 'PUT'
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(qrinfo)
})
.then((data) => {
let url = data.url;
if(url.includes('/leave.html')) {
window.location.replace('/leave.html');
}
else {
console.log("Page not changed.");
}
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
You can check if the path name is included in the url instead by using .includes() so changing ports won't be an issue.