Send data per Ajax to Controller in Laravel 5.8 - ajax

I have the Ajax request
Here is the code of script
<script>
$('#variant_model').change(function(){
var value = $('select#variant_model').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:"POST",
url: "showVariantModel",
data: value,
success: function(data){
alert(data);
}
})
});
</script>
When I put in my web.php the code
Route::post('/showVariantModel', function(){
if(Request::ajax()){
return var_dump(Response::json(Request::all()));
}
});
Everything looks fine and I receive the response in my alert.
But when I want to put everything into controller I receive the error 500 in the console
Below I will add my code from my web.php and Controller.
Framework is Laravel 5.8
//web.php
Route::post('/showVariantModel', 'VariantsController#checkAttribute');
//VariantsController.php
public function checkAttribute()
{
if(Request::ajax()){
return var_dump(Response::json(Request::all()));
}
Who knows what am I doing incorrect, please give an advice...
Updating the error
https://i.stack.imgur.com/iDvvG.jpg
Thank's Md.Sukel Ali I updated my controller. Not it looks
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Variants;
class VariantsController extends Controller
{
public function checkAttribute(Request $request)
{
if($request->ajax()){
return response()->json($request->all());
}
}
}
Everything works fine now.
Thank you.

The closing tag is missing
public function checkAttribute()
{
if(Request::ajax()){
return Response::json(Request::all());
}
}

Instead of blinding guess what happening under the hood of ajax call. I suggest you to learn how to debug ajax request.
Go to your browser right click and Inspect then go to Network tab then you can see your request. Click on your request then look for response tab. There you can find exactly what happened.
public function checkAttribute(Request $request)
{
if($request->ajax())
{
return response()->json($request->all());
}
}

You need to add imports in your controller:
use Illuminate/Http/Request;
use Illuminate/Http/Response;

Related

function __construct in BaseController

I want to declare a global variable. Here are my actions
BaseController
protected $header_data;
public function __construct()
{
$this->header_data = HeaderData::all();
View::share('data', $this->header_data);
}
Next, in the Blog page controller, let's say I write this
$this->header_data;
And on the page itself in php.blade
<h1>{{ $data }}</h1>
But I get completely all the data from the model, and I only need a field data
[{"id":3,"url":"\/blog","data":"<title>Blog<\/title>\n<meta name=\"description\" content=\"Blog\" \/>","created_at":"2021-10-19T11:24:41.000000Z","updated_at":"2021-10-19T11:24:41.000000Z"}]
when I click on the like to update the data, I reload the page using
window.location.reload();
Can this somehow be done without reloading the page?
Yes, by not using window.location.reload();.
$.ajax({
url: href,
type: 'POST',
success: function () {
$(this).addClass('active');
},
error: function (jqXhr, status, error) {
alert(error);
},
});
Change your PHP so it doesn't return the complete page for POST requests to the /article/...?type=heart route.
In case of a "like" functionality, you practically only need feedback whether it has worked (the like was registered), or not (in which case you might want to display an error).
Your server could simply respond with status code 204 (No Content) in the success case.

Problem Ajax with Laravel 5.7 and eloquent

Controller path
Route::get('ajax-BodegasFind','AjaxController#ajaxBodegasFind')->name('ajax.bodegasfind');
Function "ajaxBodegasFind"
public function ajaxBodegasFind(Request $Request)
{
$Tienda = new Tienda;
$Bodegas = $Tienda::find($Request)->bodegas();
return $Bodegas->toJson();
}
Ajax script
$(document).ready(function(){
$('#cod_tienda').change(function(e){
e.preventDefault();
var ctienda = $("#cod_tienda").val();
$.ajax({
type: 'get',
url:'{{route('ajax.bodegasfind')}}',
data: {
"ctienda": ctienda,
},
dataType: 'json',
success: function(data){
console.log(data);
$('#cod_bodega').html(data);
}
});
});
});
Model Tienda
public function bodegas(){
return $this->hasMany('genericlothing\Bodega','cod_tienda','cod_tienda');
}
Error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error) /ajax-BodegasFind?ctienda=3:1
Method Illuminate\Database\Eloquent\Collection::bodegas does not exist.
Or Method toJson does not exist, it's very weird.
Pd:
I already tried the csrf token and everything is the same.
you change your code like this:
public function ajaxBodegasFind(Request $Request)
{
$Bodegas = (Tienda::find($Request->id))->bodegas;
return $Bodegas->toJson();
}
you should have bodegas relationship method in your Tienda
And in find method your should send id not Request object .Maybe you change your find methods . its ok if you do it
hope its help
You cannot call a static find method on an instance object and you cannot pass request object in find method. It only takes primary key id. You should change your code the following two ways. You must have badge relation in your model(if you want to get related data) . Otherwise just call the property.
Option 1.
public function ajaxBodegasFind(Request $Request)
{
$Tienda = new Tienda;
$Bodegas = $Tienda->find($Request->id)->bodegas;
return $Bodegas->toJson();
}
Option 2.
public function ajaxBodegasFind(Request $Request)
{
$Bodegas = Tienda::find($Request->id)->bodegas;
return $Bodegas->toJson();
}

Empty request data from ajax in laravel 5.4

I want to change a value based on the selected year and week with ajax.
This is my ajax function:
function changeBekeken() {
var year = $("#jaar-nr").val();
var week = $("#week-nr").val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "/planning/viewed",
type: "POST",
data: {
year_nr: year,
week_nr: week
},
dataType: "json",
success: function(data) {
alert(data);
}
});
}
$(document).ready(function(){
$("#week-nr").change(function(){
changeBekeken();
});
$("#jaar-nr").change(function(){
changeBekeken();
});
});
This is the route:
Route::post('/planning/viewed', 'PlanningController#viewed');
The data is send to a controller function:
public function viewed(Request $request) {
$check = DB::table('planning_files')
->where([
['user_id', Auth::user()->id],
['created_year', $request->input('year_nr')],
['week', $request->input('week_nr')],
])
->select('seen')
->first();
if($check) {
return json_encode($check, JSON_PRETTY_PRINT);
} else {
return json_encode(false);
}
}
However even when I use $request->all(); request is always empty. My function will always return false. Pretty much this exact same function works on another page, but I can't seem to get this one working.
I have tried adding some extra information to the ajax function, like content type and data type, but none seem to work.
Any tips?
Edit 1
These are the namespaces and classes I use in my controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
use Auth;
use Storage;
Edit 2
When I copy the function to another page it works properly. It has something to do with the content on the page I use the ajax function on. Probably some conflict with the token. I will try to resolve this and post the answer for others if they might have the same problem in the future.

Cakephp Ajax post data not working in set method

I am trying sent one data from one view to another controller and set the data for another view. Here is ajax code working fine
$.ajax({
url: "<?php echo Router::url(array('controller'=>'users','action'=>'exchange_process'));?>",
type: "POST",
data: {"point_origin": point_origin },
success: function(){
alert("success");
}
});
In controller I have received this data by bellow code
public function exchange_process()
{
if($this->request->is(array('post', 'ajax'))) {
$point_origin=$_POST['point_origin'];
}
$this->set("pointorg",$point_origin);
}
In another view I have tried
<?php echo $pointorg ?>
It's not working.
if I try
public function exchange_process()
{
if($this->request->is(array('post', 'ajax'))) {
// $point_origin=$_POST['point_origin'];
}
$point_origin=123;
$this->set("pointorg",$point_origin);
}
It's working,but if I try
public function exchange_process()
{
if($this->request->is(array('post', 'ajax'))) {
// $point_origin=$_POST['point_origin'];
$point_origin=123;
}
$this->set("pointorg",$point_origin);
}
It's not working.
change your if clause to:
if($this->request->is('post') || $this->request->is('ajax')) {
and it should be working fine
CakePHP 2.3 doesnot support array of type headers, please check
http://book.cakephp.org/2.0/en/appendices/2-4-migration-guide.html#cakerequest
you will need to check individually or use Ajax only if request is to be sent using Ajax only.

Zend Framework: How to call a Function (not a Controller Action) using ajax?

Assume that I have a public function in IndexController called test():
public function test(){
//some code here
}
In index.phtml view file, I want to use JQUERY AJAX to call test() function but have no idea about this.
Code:
Click me to call test() function()
<script>
callTestFunction = function(){
$.ajax({
type: "POST",
Url: ***//WHAT SHOULD BE HERE***
Success: function(result){
alert('Success');
}
});
}
</script>
I would suggest writing an action for it. If there is logic inside of test() that you need other actions to be able to use, the factor that out.
There are a couple of reasons for having it be its own action:
You can test the results of the action directly instead of having to go through a proxy.
You can take advantage of context switching depending on if you need JSON returned or HTML
It is an action that you are trying to hit via AJAX, so there's no need to hide it.
Remember that not every action has to be its own full fledged page. One thing to make sure you do is disabling the auto-rendering of the view inside this action so it doesn't complain about not being able to find it.
public function ajaxproxyAction(){
if (is_callable($_REQUEST['function_name'])) {
return call_user_func_array($_REQUEST['function_name'], $_REQUEST['function_params'])
}
}
<script>
callTestFunction = function(){
$.ajax({
type: "POST",
Url: '/controller/ajaxproxy/',
data: { function_name: 'echo', function_params: 'test' }
Success: function(result){
alert('Success');
}
});
}
</script>
public function ajaxproxy2Action(){
if (method_exists($this, $_REQUEST['function_name'])) {
$retval = call_user_func_array(array($this, $_REQUEST['function_name']), $_REQUEST['function_params']);
echo json_encode(array('function_name' => $_REQUEST['function_name'], 'retval' => $retval));
die;
}
}
just think about this way ;)

Resources