Ajax calling Area Controller - ajax

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)
}
});

Related

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.

Laravel ajax form call jQuery function

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>

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

jQuery, AJAX and Codeigniter - form submit does not work

I'm new to all this AJAX thing so I thought that good learning will be to build simple TODO list. Below is index.php and corresponding controller. Index gets loaded without errors, but when I submit my task nothing is happening. Only page gets reloaded. Database is still empty.
index.php
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<h1>Todo</h1>
<form id="add" >
<input type="input" name="task" />
<input type="submit" value="Add" /><br />
</form>
<script>
$("form").submit(function() {
var value = $("input:first").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>todo/add/" + $("input:first").val(),
dataType: 'text',
success: function()
{
var newP = $('<p />').text(value);
$(".todos").append(newP).fadeIn(1000);
}
});
return true;
});
</script>
<div class="todos"></div>
<p>ZaƂadowano w <strong>{elapsed_time}</strong></p>
</body>
controller/todo.php
<?php
class Todo extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('todo_model');
}
public function index($type = NULL)
{
$this->load->view('todo/index');
}
public function add($data)
{
$this->Todo_model->add($this->input->xss_clean($data));
}
}
?>
Update:
todo_model.php:
<?php
class Todo_model extends CI_Model {
public function __construct()
{
parent::__construct();
$this->load->database();
}
public function add($data)
{
$this->db->insert('todo', $data);
}
public function get()
{
return $this->db->get('todo')->result();
}
}
?>
Try using this:
public function add($data)
{
$this->Todo_model->add($data);
}
instead of:
public function add($data)
{
$this->Todo_model->add($this->input->xss_clean($data));
}
UPDATE:
JAVASCRIPT:
$.ajax({
method: 'POST',
url: '<?php echo base_url(); ?>todo/add/',
data: 'data=' + $("input:first").val(),
success: function(resp) {
//rest processing
}
});
CONTROLLER:
public function add()
{
$this->Todo_model->add($this->input->post('data'));
}
You'll need to use a debugger like Firebug console to see what the reply of the server is to your request.
In your script section
$(function(){}
is missing, which should be wrapped around your jQuery
use something like this to stop the form from submitting:
if (evt.preventDefault()) {
evt.preventDefault();
}else{
evt.returnValue = false;
}
Try this one then debug with firebug by clicking on firebug icon then clicking on Console to see what you submit and how the response is
var id = 1;
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>todo/add/",
data: {id : id},
success: function()
{
var newP = $('<p />').text(value);
$(".todos").append(newP).fadeIn(1000);
}
});

Resources