I am trying to achieve simple Ajax call in my web application, unfortunately it is not working.
Html code
<li id="decorative_items">
Decorative Items
</li>
Ajax code:
$(document).ready(function() {
var id = 2; /* This has nothing to do with the code */
$("#decorative_items").bind("click", function() {
alert("click event fired"); /*This is working*/
$.ajax({
type:'POST',
url:'/getDecorativeItems',
data: {'id' : id},
success:function(response) {
alert("foo");
}
});
});
});
routes/web.php
Route::post('/getDecorativeItems', 'ajaxController#fetchDecorativeItems');
ajaxController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Http\Request;
class ajaxController extends Controller
{
function fetchDecorativeItems(Request $request) {
$msg = "Reached Controller";
return response()->json(array('msg'=> $msg), 200);
}
}
I have read all the answers to related questions and other online posts but I am unable to find the error.
Note: The code is working fine, there is no syntax error but I am unable to achieve the intended output. The intended output I am looking for is alerting "foo" using Ajax
Thanks in advance
Turn on your chrome devtool, check on network -> XHR in list of your XHR request, click on your ajax request (Case your ajax request fase, it has red color ) -> preview to see what really happen, if somethings wrong on your Laravel backend code, it also show here.
See the image bellow:
Hope this helfull, don't debug by print an alert()
I got the solution.
I was missing CSRF in my Ajax function call
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
Related
I have a Controller in my Laravel project called Clientecontroller, it works perfectly. Inside it, I have a method called listar() who brings me client's information.
public function listar(Cliente $cliente) {
$clientes = DB::table('clientes')
->where('documento_id', 1)
->first();
return $clientes;
}
Sure it has some troubles but my main question is, how I call this listar() function from a view with Angular or Ajax or whatever could work.
I am working in a selling system and I have to bring the client information before selecting anything else. I want to write the ID number from the clients in my view and bring the client information from my controller without reloading. But I am still stuck in the processing reaching the listar() function.
Thank you very much.
in your routes.php file add
Route::post('/cliente', 'Clientecontroller#listar');
And now use your ajax call in order to send data to /cliente the data will be sent through to your listar method in the ClienteController.
$.ajax({
type: "POST",
url: '/cliente',
data: { id: 7 }
}).done(function( msg ) {
alert( msg );
});
This question was answered, for more details head over here
1. The classical HTML approach
Let's say you have a button on your page :
<button id="call-listar">Call !</button>
You could send an HTTP Request to your Laravel application like that :
document.querySelector('#call-listar').addEventListener('click', (e) => {
// Use the fetch() API to send an HTTP Request :
fetch('/the-url-of-listar-controller')
.then(response => response.json())
.then(json => {
// Do what you want to do with the JSON
});
});
📖 You can find a very usefull documentation about the fetch() API here : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
2. Inside an Angular Component
This is an other story here, let's say you have this button in your HTML Template :
<button (click)="callListar()">Call !</button>
Inside your TypeScript, you could use HttpClientModule to send an HTTP Request to your Laravel App :
class MyComponent {
constructor(private http: HttpClient){}
callListar() {
this.http.get('/url-of-listar-controller')
.subscribe(response => {
// Do what you want with the response
});
}
}
WARNING : HttpClientModule needed !
You must import the HttpClientModule inside your AppModule or any other module of your Angular App where you want to use this component :
import { HttpClientModule } from '#angular/common/http';
#NgModule({
declarations: [...],
imports: [HttpClientModule]
})
I'm using Laravel 5.2. On my index page, I've got a button to add a new entry, which brings up the form in a lightbox. This form then submits via the create method.
I also have each entry listed on this page, with the ability to edit them inline, which submits via the update method.
I've setup validation via a Request. This means when someone misses something on the add, it redirects to the index method with errors. The errors only show though, when the lightbox is triggered by the user.
I know I can use $errors to see any errors, but I don't see how I can differentiate between the create and update forms for the sake of forcing the lightbox to appear on reload with create errors. Is there a way to do that?
Update:
Suggestion was made to use AJAX to bypass the reload issue, but now I'm getting a 422 return:
AJAX call:
(function(){
var submitAjaxRequest = function(e){
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST';
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function(data){
console.log(data)
}
});
e.preventDefault();
}
$('form[data-remote]').on('submit', submitAjaxRequest);
})();
Request:
public function response(array $errors)
{
$response = parent::response($errors);
if ($this->ajax() || $this->wantsJson()) {
return $response;
}
return $response->with('requestMethod', $this->method());
}
I've also tested the ajax call and it works fine when the validation rules are met. It only fails if the validation comes back with something incorrect in the input.
You could override the response method so that you can flash the type of request.
In you Request class you could add
public function response(array $errors)
{
$response = parent::response($errors);
if ($this->ajax() || $this->wantsJson()) {
return $response;
}
return $response->with('requestMethod', $this->method());
}
(With ajax you wouldn't need to worry about the page reload so we can just return the original response.)
In the above I'm assuming you're using POST for your create methods and PUT or PATH for your update methods. If this is not the case you could use a way that make sense to you to differentiate between the requests.
Then in your view you could do something like:
#if(session('requestMethod') == 'POST')
https://laravel.com/docs/5.2/responses#redirecting-with-flashed-session-data
If you are going to use ajax, as I mentioned in the comment above, you will need to make sure you use the error method within the ajax call:
$.ajax({
type: method,
url: form.prop('action'),
data: form.serialize(),
success: function (data) {
console.log('success', data)
},
error: function (data) {
console.log('error', data)
}
});
Hope this helps!
I'm trying to load a calendar on my page using AJAX/Laravel-5. The URL the AJAX is posting to exists in my routes.php file. However for some reason I keep getting the following error:
Class App\Http\Controllers\AdminBookingsController does not exist
My jQuery call:
(function($){
$.fn.initCalendar = function(token,month,location) {
$('#calendar-overlay-wrap').html('');
$.ajax({
url: '/admin/reports/bookings/butchers',
type: 'post',
data: {
_token: token,
month: month,
location_id: location
},
dataType: 'json',
success: function(json) {
if(json['error']) {
$('#calendar-overlay-wrap').html(json['msg']);
}
$('#calendar').html(json['calendar']);
}
});
}
})(jQuery);
$(document).ready(function() {
$.fn.initCalendar(
$('input[name=_token]').val(),
$('#month').val(),
$('#location_id').val()
);
});
My routes.php file:
Route::post('admin/reports/bookings/butchers', 'AdminBookingsController#genButchersReport');
My controller file:
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Booking;
use App\Location;
use App\ClassType;
use App\Classes;
use App\Http\Requests\BookingSearchRequest;
use App\Http\Requests\UpdateBookingRequest;
use App\Http\Requests\BookingReportAccountsRequest;
use Response;
use Excel;
use DB;
class AdminBookingsController extends Controller
{
/**
* Generate booking report for butchers.
*
* #return Response
*/
public function genButchersReport()
{
echo "Hi!...";exit;
}
}
I have tried running composer dump-autoload but this does not seem to have any effect on the error.
Please help.
I managed to resolve this as my controller was inside a sub folder. I changed my route and now it works.
Route::post('admin/reports/bookings/butchers', 'Admin\AdminBookingsController#genButchersReport');
This error popped up for me when I accidentally typed return = $variablename instead of return $variablename in one of my controller files. Maybe it will help somebody.
I have question about call to my module action via ajax.
I'd like call to class in my module via ajax. But best solution for me is call to clean class. Not extends Module.
I don't know hot can I make url without add article to database and add module to him.
I use JQuery instead mooTools but js framework is not important. Most important is call to php class by ajax.
I have ajax module. But if I call to ajax.php required is module id from tl_module table. I don't want use this table. (Ajax will be very often calling, I prefer to don't load all contao mechanism. It should be very fast).
Thanks in advance for answers.
I found the answer for Contao >3.x in a GitHub issuse(german)
At first do in your Front-end Template:
<script type="text/javascript">
var data = {};
data["REQUEST_TOKEN"] = "<?php echo REQUEST_TOKEN ?>";
$(document).ready(function(){
$("#trigger").click(function(event){
$.post(
'<?php echo \Contao\Environment::get('requestUri')?>',
data,
function(responseText) {
alert(responseText);
}
).fail(function( jqXhr, textStatus, errorThrown ){ console.log( errorThrown )});
event.preventDefault();
});
});</script>
Important is the
- data["REQUEST_TOKEN"] -> if you do not add it, the POST-request will not reach your module:
public function generate()
{
if ($_SERVER['REQUEST_METHOD']=="POST" && \Environment::get('isAjaxRequest')) {
$this->myGenerateAjax();
exit;
}
return parent::generate();
}
//do in frontend
protected function compile()
{
...
}
public function myGenerateAjax()
{
// Ajax Requests verarbeiten
if(\Environment::get('isAjaxRequest')) {
header('Content-Type: application/json; charset=UTF-8');
echo json_encode(array(1, 2, 3));
exit;
}
}
If you want to do the ajax via GET you do not need the reqest token but the jquery funktion $get();
I would suggest you to use Simple_Ajax extension.
In this case you dont need to use Database and you can do pretty much anything you can do normally with Jquery ajax calls.
It works with Contao 2.11 and you can call your php class with it.
I find it much easier to use than ajax.php .
You can get it from : https://contao.org/de/extension-list/view/simple_ajax.de.html
Copy SimpleAjax.php to Contao's root folder.
Go to [CONTAO ROOT FOLDER]/system/modules and create a php file like following :
class AjaxRequestClass extends System
{
public function AjaxRequestMethod()
{
if ($this->Input->post('type') == 'ajaxsimple' )
{
// DO YOUR STUFF HERE
exit; // YOU SHOULD exit; OTHERWISE YOU GET ERRORS
}
}
}
Create a folder called config with a php file like following ( You can hook you class to TL_HOOKS with class name - class method, simple_ajax will execute you method whenever a ajax call is made ):
$GLOBALS['TL_HOOKS']['simpleAjax'][] = array('AjaxRequestClass','AjaxRequestMethod'); // Klassenname - Methodenname
Now you can easily make ajax calls with simply posting data to SimpleAjax.php:
$.ajax({
type: "POST",
url: "SimpleAjax.php",
data: { type: "ajaxsimple" },
success: function(result)
{
//DO YOUR STUFF HERE
}
I am using a class to do some CRUD stuff on a database, this one (http://net.tutsplus.com/tutorials/php/real-world-oop-with-php-and-mysql) I am going to use jquery to check the if the username has been registered already.
I could just create a php file specifically for that task, but would just like to extend the class and create a method callled checkname().
How can I call this in jquery?
You can use jQuery to make ajax call to a php file following:
PHP [suppose, test.php]
<?php
class ABC extends XYZ {
public function checkname() {
if(isset($_POST) && !empty($_POST['name'])) {
echo json_encode(array('status' => 'done'));
}
}
}
$ins = new ABC();
$ins->checkname(); // calling the function checkname
?>
jQuery:
$.ajax({
url: 'test.php', // write the url correctly
type: 'post',
data: "name=XYZ&location=PQR"
}).done(function(response) {
console.log(response.status); // will log done
}).fail(function(jqXHR, textStatus) {
console.log("Failed: " + textStatus);
});
It is just an example.
You'll need to use jQuery's Ajax functionality to access a PHP page that calls that function. You can't directly call a PHP function via Ajax, something on the backend has to be set up.