Laravel ajax form call jQuery function - ajax

I'm starting to learn Laravel, first time and first project.
I have my custom login form working, but want to improve it, ajax request works fine, but can't call a JS function. The documentation of the template I'm using says to trigger with JS.
I've tried calling the function directly:
error: function() { // What to do if we fail
One.helpers('notify', {type: 'danger', icon: 'fa fa-times mr-1', message: 'Your message!'});
}
Also tried to call with jQuery.trigger:
error: function() { // What to do if we fail
jQuery.trigger(One.helpers('notify', {type: 'danger', icon: 'fa fa-times mr-1', message: 'Your message!'}););
}
Nothing seems to work.
Ajax Function:
<script type="text/javascript">
/**
* #return {boolean}
*/
function LoginUser()
{
var formData = {
username: $("input[name=login-username]").val(),
password: $("input[name=login-password]").val()
};
// Ajax Post
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
url: "/login",
data: formData,
cache: false,
success: function(){ // What to do if we succeed
},
error: function() { // What to do if we fail
}
});
return false;
}
</script>
What I expected is a notification message like this:
What I get:
Absolutely nothing, nothing shows up on the page.
Laravel Routes:
Route::get('/', function () {
if (Auth::check()) {
return Redirect::to('dashboard');
}
return view('auth.login');
});
Route::match(['get', 'post'], '/dashboard', function () {
return view('dashboard');
});
Route::group(['middleware' => 'App\Http\Middleware\LoginMiddleware'], function () {
Route::match(['get', 'post'], '/dashboard/', 'HomeController#dashboard');
Route::match(['get', 'post'], '/admin/users', 'HomeController#admin_users');
Route::match(['get', 'post'], '/admin/permissions', 'HomeController#admin_permissions');
});
Auth::routes();
Route::post('/login', 'Auth\AuthController#postLogin');
Route::get('/logout', 'Auth\AuthController#getLogout');

make sure you didn't miss the csrf meta tag in html head:
<head>
...
<meta name="csrf-token" content="{{ csrf_token() }}">
....
</head>
or you can simply replace the {{ csrf_token() }} with $('meta[name="csrf-token"]').attr('content') in your code, like this:
// Ajax Post
$.ajax({
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
// ...
});

U get this error, because route "login" cant accept "POST" request.
try change type: "post", to type: "get",, u should get something like this:
<script type="text/javascript">
/**
* #return {boolean}
*/
function LoginUser()
{
var formData = {
username: $("input[name=login-username]").val(),
password: $("input[name=login-password]").val()
};
// Ajax Post
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "get",
url: "/login",
data: formData,
cache: false,
success: function(){ // What to do if we succeed
},
error: function() { // What to do if we fail
}
});
return false;
}
</script>

Related

Ajax to call Symfony controller

I'm trying to call a method with ajax.
ajax connection is succeed and no error message was appeared.
the JS code
$("[id^=changeStatus]").each(function(){
$(this).on("click", function(){
const id = $(this).data('id');
console.log(id);
$.ajax({
type: "POST",
url: "{{url('change_order_status')}}",
data: id,
async: false,
})
.done(function() {
console.log('success');
})
.fail(function () {
console.log('error');
});
});
but the method in the controller seemingly not working.
controller
/**
* #Method("POST")
* #Route("/%eccube_admin_route%/", name="change_order_status")
* #param $request
* #return \Symfony\Component\HttpFoundation\JsonResponse
*/
public function changeOrderStatus(Request $request)
{
if (!$request->isXmlHttpRequest()) {
throw new BadRequestHttpException();
}
$this->logger->info("it's working");
dump($rquest);
}
I don't know what is wrong with it.
Please help.
I insert the js to every pages as an snippet is that's why it doesn't work properly.
You must return an instance of Response class in a controller . So here, what you can do is to return a JsonResponse
return new JsonResponse($request->getContent());
May be you can try this.
$("[id^=changeStatus]").each(function(){
$(this).on("click", function(){
const id = $(this).data('id');
console.log(id);
$.ajax({
type: "POST",
url: "{{ path('change_order_status') }}",
data: {
id : id
},
async: false,
})
.done(function(data) {
console.log(data)
console.log('success');
})
.fail(function () {
console.log('error');
});
});
/**
* #Route("/%eccube_admin_route%/", name="change_order_status", methods={"POST"})
* #param $request
* #return \Symfony\Component\HttpFoundation\JsonResponse
*/
public function changeOrderStatus(Request $request)
{
if (!$request->isXmlHttpRequest()) {
throw new BadRequestHttpException();
}
$this->logger->info("it's working");
$id = $request->request->get('id');
// Try to dump your request
// dd($request);
return $this->json([
'success' => true
]);
}
I just don't know what eccube_admin_route mean.
And don't forget to extend AbstractController in your controller class
This is example from my project. Try to dump your controller object and use symfony debugbar to open your ajax request, click on url columns

Trying to get the ajax form submitted data in controller in laravel

I am Trying to get the ajax form submitted data in the controller in laravel but getting nothing in controller request with the following code
ajax
$('.ace_text-input').keyup(function(e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/forksnippet/saveforksnippets',
type: 'POST',
data: $(this).serialize(),
beforeSend: function(result) {
$(".saveforksnippetbutton").attr("disabled", true);
$(".saveforksnippetbutton ").html('Auto saving...');
},
success: function(result) {
$(".saveforksnippetbutton ").html('Auto Saved');
}
});
});
Controller function
public static function saveforksnippets(Request $request)
{
return $request->post('snippet_title');
}
Please help
Add a key to your data object
$.ajax({
url: '/forksnippet/saveforksnippets',
type: 'POST',
data: {
payload: $(this).serialize(),
},
beforeSend: function(result) {
$(".saveforksnippetbutton").attr("disabled", true);
$(".saveforksnippetbutton ").html('Auto saving...');
},
success: function(result) {
$(".saveforksnippetbutton ").html('Auto Saved');
}
});
Parse the serialized data in the controller
public function saveforksnippets(Request $request)
{
parse_str($request->payload, $output);
return $output['snippet_title'];
}
PS: I have removed the static scope of the function.

Is it possible to post from custom js to .module/custom.php/controller file and get response in custom js while developing custom module in drupal8?

i have this in custom.js file in drupal modules/mymodule/js/ folder
(function ($) {
Drupal.behaviors.coorrency = {
attach: function (context, settings) {
jQuery.ajax({
url: 'modules/mymodule/custom.php',
type: "POST",
success: function(data){
console.log(data);
}
});
}
}
})(jQuery);
and i have to post to modules/mymodule/custom.php
<?php
echo "test";
?>
and return data from custom.php
You can do that by creating a controller for listening that ajax call
my_module.routing.yml
my_module.call_back:
path: '/my_module/call_back'
defaults:
_controller: '\Drupal\my_module\Controller\DefaultController::callBack'
_title: 'Call Back'
Controller
<?php
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
/**
* Class DefaultController.
*/
class DefaultController extends ControllerBase {
/**
* Your Callback
*
*/
public function callBack() {
return ["This is a test" ];
}
custom.js
(function ($) {
Drupal.behaviors.coorrency = {
attach: function (context, settings) {
jQuery.ajax({
url: '/my_module/call_back',
type: "POST",
success: function(data){
console.log(data);
}
});
}
}
})(jQuery);

recover AJAX post data with Laravel 5.5

I have an Ajax script and i have to recover the datas in a controller as POST and we have error 404 ...
Here is my JS :
function ajax() {
var values = {
'str': "Salut",
'id': "Dave & Alex",
};
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/ajax',
type: 'post',
dataType: 'json',
async: true,
data:values,
success: function (result) {
console.log(result);
},
error: function (result) {
console.log(result);
},
complete: function (result) {
console.log("complete");
}
});
};
Here are my route which is /admin/ajax and which is available to logged in admins:
Route::group(['prefix' => 'admin'], function () {
Route::group(['middleware'=>'admin'], function(){
Route::post('/ajax', 'AdminsController#majax');
});
});
In my Controller i created a method :
public function index(Request $request)
{
if($request->ajax()){
return response()->json(['status'=>'Ajax request']);
}
return response()->json(['status'=>'Http request']);
}
I have 2 issues :
1. I have an Http request displayed as result
2. How can i display the values of my "values" array ?
Thanks for your help

Ajax calling Area Controller

I am trying to call a Controller from Ajax, but I'm getting:
Failed to load resource: the server responded with a status of 404 ()
The Ajax is calling from the Admin View to the Admin Controller. I can view the Admin Page, but I'm unable to call GetAll() and GetAllUsers() from Ajax or any other method.
In Startup
app.UseMvc(routes =>
{
routes.MapRoute("areaRoute",template:"{area:exists}/{controller=Admin}/{action=Index}/{id?}");
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
In AdminController
namespace Project.Areas.Admin.Controllers
{
[Area("Admin")]
[Authorize(Policy = "AdminOnly")]
public class AdminController : Controller
{
public IActionResult Index()
{
return View();
}
public AdminController()
{
}
[HttpGet("GetAll/{page}")]
public IActionResult GetAll(int? page)
{
}
[HttpGet("GetAllUsers/{page}")]
public IActionResult GetAllUsers(int? page)
{
}
}
}
Ajax:
#section Scripts{
#await Html.PartialAsync("_ValidationScriptsPartial")
<script>
$(function () {
$.ajax({
type: "GET",
url: "/Admin/GetAll",
traditional: true,
success: function (view) {
$("Result").html(view)
}
});
$.ajax({
type: "GET",
url: "/Admin/GetAllUsers",
traditional: true,
success: function (view) {
$("userResult").html(view)
}
});
});
</script>
}
in the url you need to user /{areaName}/{controllerName}/{ActionMethod}
$.ajax({
type: "GET",
url: "/Admin/Admin/GetAllUsers",
traditional: true,
success: function (view) {
$("userResult").html(view)
}
});

Resources