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();
}
Related
I created a select with select2 js and created the ajax request:
$('#slcCidade').select2({
ajax: {
type:'POST',
url: '/get-cidade',
minimumInputLength: 3,
data: function (params) {
var query = {
search: params.term
}
return query;
},
processResults: function (data) {
return {
results: data.items
};
}
}
});
In my controller I have the following method to get data, then it returns to my page:
[Route("get-cidade/{search:regex(^[[a-zA-Z]])}")]
[HttpPost]
public async Task<JsonResult> GetCidade(string search)
{
var lstCidadesVM = _mapper.Map<IEnumerable<CidadeViewModel>>(await _cidadeBLL.GetByNome(search));
return new JsonResult(new { Data = lstCidadesVM });
}
The request never returns to my controller and analyzing the request I see that a 404 error has occurred
Request URL: https://localhost:44394/get-cidade?search=curvelo
Request Method: GET
Status Code: 404 Not Found
Remote Address: [::1]:44394
Referrer Policy: no-referrer-when-downgrade
Where am I doing wrong? I just need to call the method from my controller by entering the search term via AJAX.
Thanks!
I think the route you're implementing is mostly '/get-cidade/curvelo',without any data to transfer as parameter.
Select2 settings were correct, the problem was the GetCity method route in the controller, it just worked by removing {search:regex(^[[a-zA-Z]])} of the route. The method went like this:
[Route("get-cidade")]
public async Task<JsonResult> GetCidade(string search)
{
var lstCidadesVM = _mapper.Map<IEnumerable<CidadeViewModel>>(await _cidadeBLL.GetByNome(search));
return new JsonResult(new { Data = lstCidadesVM });
}
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.
I have a folder (suppose it's name is "test") outside of controller folder which contains a file name "error404.php" and my controller name is "test_controller.php" which has a method name "tst()". error404.php is a view page in where i want to access data from test_controller.php via ajax.
<script>
$(document).ready(function(e) {
$('#search_items_err').keyup(function(e) {
if($('#search_items_err').val().trim()==''){$('#sugglist').html(''); return false;}
search_key=$(this).val().trim();
var data = {
search_key: search_key
};
alert(search_key);
$.ajax({
data: data,
type: "post",
url: "test_controller/tst",
success: function(response) {
var options = JSON.parse(response);
alert(options);
}
});
});
});
</script>
My tst function is:
public function tst(){
$search_key = $_POST['search_key'];
echo "success";
}
But my ajax doesn't work. I suspect that it may contain some problems in the (url: "test_controller/tst",). So how can i solve it? What is the syntax of accessing test_controller's method from error404.php page?How do i access base url?
Take a look at this ajax concept
in your ajax function :
url : baseURL+'test_controller/search', //Make sure this url is working properly
data : {'search_key' : search_key},
in you test_controller/search
public function search()
{
//generate data and load your view
$data = "Generated Data array";
$this->load->view('test_folder/search', $data); //Load your view from application/view/ not from outside the controller
}
I'm trying to send a Backbone collection to Laravel with an Ajax Request.
I don't need to save it or update the database I just need to process the data with the Omnypay php Api. Unfortunately the Laravel Controller variable $input=Input::all() contain an empty string.
var url = 'index.php/pay';
var items = this.collection.toJSON;
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: items,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
This is the Laravel Route:
Route::post('pay','PaypalController#doPay');
And finally the Laravel Controller:
class PaypalController extends BaseController {
public function doPay() {
$input=Input::all();
}
}
Your route doesn't match, it's
Route::post('pay','PaypalController#doPay');
So the url should be
var url = 'pay';
instead of
var url = 'index.php/pay';
BTW, not sure if anything else (backnone) is wrong.
Update : toJSON is a method, so it should be (you missed ())
var items = this.collection.toJSON();
The hack solution I found to transfer a backbone collection to Laravel was to convert the collection to JSON and then wrapping it in a plain object, suitable for the jQuery Ajax POST. Here is the Code:
var url = 'index.php/pay';
var items = this.collection.toJSON();
var plainObject= {'obj': items};
$.ajax({
url:url,
type:'POST',
dataType:"json",
data: plainObject,
success:function (data) {
if(data.error) { // If there is an error, show the error messages
$('.alert-error').text(data.error.text).show();
}
}
});
Now the $input variable of my "doPay" controller function contain an array of Backbone models.
The situation, I'm making multiple ajax/json requests on the same page to a controller, which returns a JsonResult.
I know this is a problem with the session state, I've added the [SessionState(SessionStateBehavior.Disabled)] attribute on my controller class, but nothing seems to work, my second ajax request just wont get the return data.
the controller:
[SessionState(SessionStateBehavior.Disabled)]
public class IndexController : Controller
{}
the two json methods:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetLatestListJSON()
{
Thread.Sleep(5000);
ArticleRepository repo = new ArticleRepository();
IList<ArticleModel> list = repo.GetLatestContent(10);
return Json(list, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetCustomerJSON()
{
Thread.Sleep(5000);
CustomerRepository Repo = new CustomerRepository();
IList<Customer> cust= Repo.GetCustomer();
return Json(cust, JsonRequestBehavior.AllowGet);
}
The second ajax call, the other one is very similar, I never get to see the 'succes'-alert.
<script type="text/javascript">
$(document).ready(function () {
alert('before');
$.getJSON("/Index/GetCustomerJSON", null, function (data) {
alert('succes');
$("#loadingGifVideo").hide();
$.each(data, function (index, mod) {
});
});
});
Thanks guys :)
If you put a break-point in your GetCustomerJSON method and run this in Visual Studio does the method ever get called? It does
EDIT
Try switching from getJSON to the ajax method so you can capture any errors. Like so:
$.ajax({
url: "/Index/GetCustomerJSON",
dataType: 'json',
data: null,
success: function (data) { alert('success'); }
error: function (data) { alert('error'); }
});
Do you get an "error" alert?