Can't call a custom method on a controller from AJAX - php

I am trying to call a controller function from an AJAX call. The view loads from the same controller, but I'm not able to call the function.
Here is the controller code:
// This function will get ajax call where pass two variables and a method name doSomeAction
class Posts extends \Core\Controller
{
public function addNewAction()
{
View::renderTemplate('Posts/addnew.html', [
// 'posts' => $posts
]);
}
public function doSomeAction()
{
echo "here";
// your action code ....
}
}
Here is my Ajax script call function
<script>
$(".submitcontr").click(function() {
$.ajax({
url: 'POST/doSomeAction',
dataType: 'json',
data: {
id: 'value'
},
success: function (data) {
console.log(data);
},
error: function () {
alert('error');
}
});
});
</script>

Related

Get date from datepicker using Ajax with Laravel controller

i want to get the datepicker value when user selected a date and send that using ajax to a laravel controller. this code is not worked for me..
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#date').datepicker({
format: 'dd-mm-yyyy',
onSelect: function(date, instance) {
$.ajax({
type: "POST",
url: '/process_date',
data: date,
success: function(result)
{
console.log(result);
}
});
}
});
here is my route,
Route::post('/process_date', 'TimeController#ajaxTime');
here is my controller,
class TimeController extends Controller
{
public function ajaxTime(Request $request)
{
$data = $request->all(); // This will get all the request data.
dd($data); // This will dump and die
}
}
Try changing your code to this because I have been reading the documentation and testing it with some code of my own and this is what I came up with
$('#date').datepicker({
format: 'dd-mm-yyyy',
}).on('changeDate', function(e) {
$.ajax({
type: "POST",
url: '/process_date',
data: {
date: e.date.toString(),
},
success: function(result) {
console.log(result);
},
error: function (error) {
console.log(error);
}
});
})
and also change your TimeController class from
class TimeController extends Controller
{
public function ajaxTime(Request $request)
{
$data = $request->all(); // This will get all the request data.
dd($data); // This will dump and die
}
}
to
class TimeController extends Controller
{
public function ajaxTime(Request $request)
{
return $request->all(); // This will get all the request data.
}
}
to receive better results in your browser console.

Laravel 5: Fetch ajax data in route and pass to controller

I'm using Laravel 5 and want to make ajax call to a controller with some data:
$.ajax({
url : "/getOrgById",
data : JSON.stringify({id:1})
})
The routes.php has:
Route::get('/getOrgById', 'HomeController#getOrgById');
HomeController.php:
public function getOrgById($data) {
//code here fails with message 'Missing argument 1 for HomeController::getOrgById()
}
How can I pass the data from ajax to route and then to controller?
I think the below example is what you're looking for
Route
Route::post('/getOrgById', 'HomeController#getOrgById');
Controller
public function getOrgById(Request $request) {
$id = $request->input('id');
}
JS
var myJsonData = {id: 1}
$.post('/getOrgById', myJsonData, function(response) {
//handle response
})
You should really look into resourceful controller actions. If you are wanting to fetch an organisation by its ID then you have an organisaiton entity, so create a corresponding organisation controller. This controller can then have a method to show an organisation by on its primary key value:
class OrganisationController
{
public function show($id)
{
return Organisation::findOrFail($id);
}
}
The route for this would look like:
Route::get('/organisations/{id}', 'OrganisationController#show');
You can then request this route via AJAX like so:
$.ajax({
method: 'GET',
url: '/organisations/' + id
});
You can use Input to get your variable
public function getOrgById() {
$data = \Input::get('data')
}
You can define paramers in your route:
Route::get('/getOrgById/{id}', 'HomeController#getOrgById');
And call it through:
$.ajax({
url : "/getOrgById" + id
})
You were almost right, but when using $data in your function declaration you're actually requiring a Query String variable, rather than a form request.
You have to add your Form Request in your Controller method, like so:
public function getOrgById(Request $request){
// do something here...
return response()->json(array('foo' => 'bar'));
}
Try with this,
HTML Form
<div id="loadingResponse"></div>
{!!Form::open(array('url'=>'test/submit', 'id'=>'submitForm','method'=>'POST'))!!}
{{Form::token()}}
<input type="text" name="data"/>
<button type="submit" class="btn btn-small btn-info">Send Data</button>
{{Form::close()}}
JS Ajax
$("#submitForm").submit(function(event) {
event.preventDefault();
$.ajax({
url : 'test/submit',
data : new FormData($("#submitForm")[0]),
dataType : 'JSON',
type : 'POST',
beforeSend: function(){
$("#loadingResponse").html("<img src='{{asset('img/loading.gif')}}' />");
},
success: function(response){
console.log(response);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Error '+xhr.status+' | '+thrownError);
},
});
});
PHP Route
...
Route::post("test/submit","TestController#submit");
...
PHP Controller
class TestController extends Controller
{
...
public function submit(Request $request)
{
response()->json(['msj' => $request->input('data')]);
}
...
}
ajax:
$.ajax({
type:'get',
url:'/getOrgById',
data:{
id:1
},
success:function(res){
}
});
routes.php:
Route::get('/getOrgById', 'HomeController#getOrgById');
HomeController.php:
public function getOrgById(Request $request) {
dd($request);
}

CakePHP - How to pass url with ajax?

I'm using cakePHP 3.0 and I have a problem while using ajax. Indeed, I would like to execute the action "viewTab" of my controller "SpecimensController" on an array coming from my view "specimen"
<script type="text/javascript" >
var tab = new Array();
function updateResult(){
$.ajax({
type:"POST",
url:"<?php echo Router::url(array('controller'=>'specimens','action'=>'index'));?>",
data:{datas: $("select[name='filtreVariable\\[\\]']").map(function(){return $(this).val();}).get()},
dataType: 'text',
async:false,
success: function(data){
alert('success');
},
error: function (data) {
alert("error");
}
});
}
$("#filtre").submit(function(){
updateResult();
});
</script>
The action "viewTab" is just doing:
echo "success";
But I can't find the right url so the function success can be called. I tried many things and I always have the function error of ajax that is called. :/
If you haven't yet, place this line of code in your AppController where your initialize function is:
public function initialize()
{
parent::initialize();
$this->loadComponent('RequestHandler');
}
In your controller for the function you're calling via ajax, try something like this:
public function index()
{
$data = ['testing'];
$this->set(compact('data'));
$this->set('_serialize', 'data');
}
http://book.cakephp.org/3.0/en/controllers/components/request-handling.html

prestashop ajax controller call

I am trying to call controller in module using Ajax in prestashop 1.5, and I'm having hard time doing this.
I've created controller in module under the path:
$refresh_url = ($this->_path)."front/blockdiscoversellers.php";
and made instructions for button in js like:
var refresh = {
call: function() {
var $refresh = $("#manufacturer-refresh");
$refresh.click(function(e) {
refresh.ajax();
e.preventDefault();
});
},
ajax: function() {
var url = $("#manufacturer-refresh").data("url");
$.ajax({
url: url,
type: 'get',
data: {
controller : 'BlockDiscoverSellers',
ajax : true
},
dataType: "json",
success: function(data) {
console.log(data);
}
});
}
};
and the body of controller looks like :
class BlockDiscoverSellers {
public function __construct()
{
die(var_dump($this->refreshManufacturers()));
}
public function refreshManufacturers()
{
$result = array("test" => "TESTER");
return Tools::jsonEncode($result);
}
}
I'm getting success in Ajax call but it looks like class and constructor are not initiated, so I am quite stuck with this problem.
It appears that prestashop when you use ajax call uses only structural type of programming. That means in ajax call there can be no class of any sort bootstrap will never initiate it even with controller parameter, and you have to die at the end of file ...

WordPress ajax function in child class

If i have this classes
class something {
public function __construct() {
add_action('wp_ajax_ajax_func', array( $this, 'ajax_func' ) );
}
public function ajax_func() {
}
}
class stchild extends something {
public function __construct() {
}
public function ajax_func() {
echo "Test child1";
}
}
How to call only ajax_func function in stchild class by ajax ?
when i try this code
jQuery.ajax({
url: 'admin-ajax.php',
data: {action : 'ajax_func'},
success: function(data){
console.log(data);
}
});
it get all functions which called ajax_func, I want to define specific class to get this function from it.
Note that there is many child classes from something class and all are activated.
You could wrap it inside an action function.
add_action( 'wp_ajax_do_something', 'my_do_something_callback' );
function my_do_something_callback() {
$object = new stchild;
$object->ajax_func();
die();
}
JS:
jQuery.ajax({
url: ajaxurl, // Use this pre-defined variable,
// instead of explicitly passing 'admin-ajax.php',
data: { action : 'do_something' },
success: function(data){
console.log(data);
}
});

Categories