Laravel cannot retrieve data from multiple model with Ajax - javascript

Hi I am beginner with Ajax at the Laravel. I wanted to fetch data with Laravel Eagerload function to my blade modal.
This is my Expenses Model
protected $fillable = [
'name',
'surname',
'email',
'password',
'status',
'role',
];
protected $hidden = [
'password',
'remember_token',
];
public function Expense () {
return $this->hasMany(ExpensesModel::class);
}
This is my Expenses Model
`
{
use HasFactory;
protected $table = 'expenses';
protected $fillable = [
'id',
'emp_id',
'expense_input_date',
'expense_type',
'expense_category',
'reason',
'status'
];
public function UserExpense () {
return $this->belongsTo(User::class, 'emp_id' );
}
My controller
This is My controller function
public function edit (Request $request) {
$req_id = array('id' => $request->id);
if($request->ajax()) {
$employee = ExpensesModel::with('UserExpense')->where('id' ,$req_id)->first();
return response()->json($employee);
}
}
This is my blade script
`
function editFunc(id){
$.ajax({
type:"POST",
url: "{{ url('/expenses/advancedtable/edit') }}",
data: { id: id },
dataType: 'json',
success: function(res){
$('#EmployeeModal').html("Edit Employee");
$('#employee-modal').modal('show');
$('#id').val(res.id);
$('#emp_id').val(res.name);
$('#expense_input_date').val(res.expense_input_date);
$('#expense_type').val(res.expense_type);
$('#expense_category').val(res.expense_category);
$('#expense_slip_no').val(res.expense_slip_no);
$('#expense_amount').val(res.expense_amount);
$('#currency').val(res.currency);
$('#description').val(res.description);
}
});
}
I tried everyting but it does not work. I wanted to retrive user name from User Model by using foreign key on the Expenses model emp_id.
is there something I missed somewhere can you help me with this.
Thank you.

Here how its work.
First of all change relationship in your User and Expenses model like this.
// User Model
public function userExpense() {
return $this->hasMany(ExpensesModel::class,'emp_id','id');
}
// ExpensesModel
public function user() {
return $this->hasOne(User::class,'id','emp_id');
}
Then change your controller function.
// controller function
public function edit (Request $request) {
$req_id = $request->id;
$employeeExpense = ExpensesModel::with('user')->where('id' ,$req_id)->first();
return response()->json($employeeExpense);
}
Then change your ajax sucess function.
// ajax sucsess function
success: function(res) {
console.log(res); // to view your response from controller in webbrowser's console
$('#EmployeeModal').html("Edit Employee");
$('#employee-modal').modal('show');
$('#id').val(res.id);
$('#emp_id').val(res.user.name); // it will print user name
$('#expense_input_date').val(res.expense_input_date);
$('#expense_type').val(res.expense_type);
$('#expense_category').val(res.expense_category);
$('#expense_slip_no').val(res.expense_slip_no);
$('#expense_amount').val(res.expense_amount);
$('#currency').val(res.currency);
$('#description').val(res.description);
}
when you use 'with' eloqunt method it will add relationship function name to your query result, so you want to get user details then you should be do like res.user.userfield this is applicable for hasOne only.
For other relationship you will refer to this https://laravel.com/docs/9.x/eloquent-relationships

Related

how to pass data coming from laravel query as a json object to the function in javascript

i am actually using graphs in my project for which i am passing dynamic data from controller to blade and then in the js script. The js function in the blade accept the array of objects and i dont know how to assign the data from the controller to that js function.
$data['typesBasedProperties'] = DB::table('properties')
->join('property_types', 'properties.property_type', 'property_types.id')
->select('property_types.types as label', DB::Raw('COUNT(properties.id) as value'))
->whereIn('properties.id', $property_ids)
->groupBy('label')
->get()
->toJson();
and this is the js function
var donutChart = function(){
Morris.Donut({
element: 'morris_donught',
data: [
{
label: " Download Sales ",
value: 12,
}, {
label: " In-Store Sales ",
value: 30
}, {
label: " Mail-Order Sales ",
value: 20
}
],
resize: true,
redraw: true,
colors: ['#2b98d6', 'rgb(59, 76, 184)', '#37d159'],
//responsive:true,
});
}
I think you need to do something like this:
<script>
var typesBasedProperties = {!! $typesBasedProperties !!}
</script>
After this you have typesBasedProperties object available in all your js code.
Check out laravel documentation for more info.
You can use ajax request to fetch data from laravel controller to javascript or JQuery.
here's some example
controller
function bbq(Request $r){
$data = DB::select('CALL bukubesar('.$r->no.')');
$node = DB::select('CALL infonode('.$r->no.')');
return array(
'data' => $data,
'node' => $node
);
}
route (I'm using Group)
Route::controller(CPembukuan::class)->group(function () {
Route::get ('/pembukuan-besar', 'bukubesar');
Route::get ('/pembukuan-besar/query', 'bbq' );
Route::get ('/pembukuan-labarugi', 'labarugi' );
Route::get ('/pembukuan-labarugi/query', 'lrq' );
});
ajax (JQuery) on html or blade file
//a variable to pass to controller (optional)
val = $('#kode').val();
$.ajax({
type: "get",
url: "/pembukuan-besar/query",
data: {
'no': val // the data represented as 'no'
},
success: function(data) {
console.log(data); // to view the data in console
//do anything you want here
}
});

Method App\Http\Controllers\ConfigSplitCleansingController::show does not exist

I got this error and I cant seem to find the bug.
This is the function in my controller.
class ConfigSplitCleansingController extends Controller
{
public function storeNewArea(Request $request)
{
$setArea = $request->setNewArea;
$decode = json_decode($setArea, true);
$activity = Activities::where('activityCode', $request->activityId)->first();
$lastrow = PubCleansingScheduleStreet::join('pubcleansingschedule_activity','pubcleansingschedule_street.pubCleansingActivityId', '=', 'pubcleansingschedule_activity.id')
->select('pubcleansingschedule_street.rowOrder')
->where('pubcleansingschedule_activity.pubCleansingScheduleParkId',$request->scheduleparkId)
->where('pubcleansingschedule_activity.activityId',$activity->id)
->orderBy('pubcleansingschedule_street.rowOrder','desc')
->limit(1)->first();
$row = $lastrow->rowOrder;
foreach ($decode as $key => $value) {
$row = $row + 1;
if($value['id'] == 0){
$schedulestreet = PubCleansingScheduleStreet::find($request->schedulestreetId);
$newsplit = new CleansingSplit;
$newsplit->pubCleansingId =$schedulestreet->pubCleansingId;
$newsplit->streetId =$schedulestreet->streetId;
$newsplit->activityCode =$schedulestreet->activityCode;
$newsplit->serviceType =$schedulestreet->serviceType;
$newsplit->value =$value['value'];
$newsplit->frequency =$schedulestreet->frequency;
$newsplit->save();
$newstreet->pubCleansingActivityId =$schedulestreet->pubCleansingActivityId;
$newstreet->pubCleansingId =$schedulestreet->pubCleansingId;
$newstreet->streetId =$schedulestreet->streetId;
$newstreet->streetName =$schedulestreet->streetName;
$newstreet->streetType =$schedulestreet->streetType ;
$newstreet->activityCode =$schedulestreet->activityCode;
$newstreet->serviceType =$schedulestreet->serviceType;
$newstreet->value =$value['value'];
$newstreet->frequency =$schedulestreet->frequency;
$newstreet->frequency_PJ =$schedulestreet->frequency_PJ;
$newstreet->rowOrder =$row;
$newstreet->save();
}
else {
$newstreet = CleansingSplit::find($value['id']);
$newstreet->value = $value['value'];
$newstreet->save();
}
}
return response()->json($newstreet);
}
}
This is my model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CleansingSplit extends Model
{
//
protected $table = 'publiccleansingsplit';
protected $fillable = [
'id',
'pubCleansingId',
'streetId',
'activityCode',
'serviceType',
'value',
'frequency'
];
}
Route
Route::post('splitpembersihan/storeNewArea', ['as' => 'storeNewArea', 'uses' => 'ConfigSplitCleansingController#storeNewArea']);
And this is the ajax
$.ajax(
{
url: '{{url("splitpembersihan/storeNewArea")}}',
type: 'post',
data: {
"setNewArea": setarray,
"scheduleparkId": scheduleparkId,
"schedulestreetId": schedulestreetId,
"splitId": splitId,
"activityId" : #if(isset($schedulestreet->activityCode))"{{ $schedulestreet->activityCode}}"#endif,
"_token": token
},
success: function (data)
{
alert("success");
window.location.replace('/splitpembersihan/splitBin/'+ PubCleansingID +'/splitValueArea');
},
error: function (data)
{
alert("error");
}
});
The error is the opposite. The data is stored successfully. However, it shows the error alert instead of the success alert. And if I just press the submit button without submitting anything, it shows the success alert.

How to call a specific php function inside a class through ajax?

I want to know how I can call the function ajax_check_login available in my User class, this class exists in user.php.
This is the basic content:
class User extends {
/**
* Class Constructor
*/
public function __construct() {
}
public function ajax_check_login() {
try {
if (!isset($_POST['username']) || !isset($_POST['password'])) {
throw new Exception('Invalid credentials given!');
}
$this->load->model('user_model');
$user_data = $this->user_model->check_login($_POST['username'], $_POST['password']);
if ($user_data) {
$this->session->set_userdata($user_data); // Save data on user's session.
echo json_encode(AJAX_SUCCESS);
} else {
echo json_encode(AJAX_FAILURE);
}
} catch(Exception $exc) {
echo json_encode(array(
'exceptions' => array(exceptionToJavaScript($exc))
));
}
}
}
and this is my ajax request:
var postUrl = GlobalVariables.baseUrl + 'application/controllers/user.php/ajax_check_login';
var postData =
{
'username': $('#username').val(),
'password': $('#password').val()
};
$.post(postUrl, postData, function(response)
{
// Some stuff..
});
How you can see I want call the function ajax_check_login available in the user.php file. But I can't access directly to this function 'cause is located inside the User class, so I should create another file to bounce the request or I can do it in the same file user.php file?
You have a typo:
class User extends {
Extends what?
Add this to user.php (outside of the class):
$allowed_functions = array('ajax_check_login');
$ru = $_SERVER['REQUEST_URI']
$func = preg_replace('/.*\//', '', $ru);
if (isset($func) && in_array($func, $allowed_functions)) {
$user = new User();
$user->$func();
}

How to implement search with two terms for a collection?

So, currently I have a collection of items where I want the user to be able to search using the name and some random text from the collection.
Here's what I have done so far:
public IEnumerable<Item> items = new[]
{
new Item { ItemId = 1, ItemName = "Apple", ItemDescription = "crispy, sweet", ItemPairing = "Walnut"},
new Item { ItemId = 2, ItemName = "Pear", ItemDescription = "slightly tart", ItemPairing = "Cheese"},
new Item { ItemId = 3, ItemName = "Banana", ItemDescription = "good source of potassium", ItemPairing = "Honey" },
new Item { ItemId = 4, ItemName = "Chocolate", ItemDescription = "Sweet and rich melting flavor", ItemPairing = "Wine"}
};
public ActionResult Index()
{
return View("Index");
}
public ActionResult Search(string search)
{
return View("Index", items.Where(n => n.ItemName.StartsWith(search)));
}
Here's the search part on the view:
<p>
<b>Search for Name:</b>
#Html.TextBox("ItemName", "", new { #class = "form-control" })
<b>Search for Text:</b>
#Html.TextBox("ItemText", "", new { #class = "form-control" })
<input id="search" type="submit" value="Search" onclick="search(ItemName,ItemText)" />
</p>
<script>
function search(ItemName, ItemText) {
$("search").click(function () {
$.ajax({
type: "POST",
url: "/Items/Search",
data: {ItemName, ItemText},
datatype: "html",
success: function (data) {
$('#result').html(data);
}
});
});
}
</script>
So that it can look something like this:
I want it so that when the user types in Apple for Name and Crispy for text, they can find the Apple item from my collection. I also want it so that if they type in either Name or Text, it will still return a matched item.
I'm not sure how to do that.
Remove the onclick attribute from the submit button and change it to
<button type="button" id="search">Search</button>
and change the script to
var url = '#Url.Action("Search", "Items")';
$("#search").click(function () {
$.post(url, { ItemName: $('#ItemName').val(), ItemText: $('#ItemText').val() }, function(data) {
$('#result').html(data);
});
})
Note you may want to consider making it $.get() rather than $.post()
and change the controller method to accept the inputs from both textboxes
public PartialViewResult Search(string itemName, string itemText)
{
var items = ??
// filter the data (adjust to suit your needs)
if (itemName != null)
{
items = items.Where(x => x.ItemName.ToUpperInveriant().Contains(itemName.ToUpperInveriant())
}
if (itemText != null)
{
items = items.Where(x => x.ItemDescription.ToUpperInveriant().Contains(itemText.ToUpperInveriant())
}
// query you data
return PartialView("_Search", items);
}
Side note: Its not clear what the logic for search is - i.e. if you enter search text in both textboxes, do you want an and or an or search
Assuming the view in the view in the question is Index.cshtml, then it will include the following html
<div id="result">
#Html.Action("Search") // assumes you want to initially display all items
</div>
and the _Search.cshtml partial would be something like
#model IEnumerable<Item>
#foreach (var item in Model)
{
// html to display the item properties
}
While CStrouble's answer will work, if you're into AJAX calls and want to sort this in a single page, you might consider using AJAX and JQuery calls.
With AJAX & JQuery:
var search = function(itemName, itemText) {
//note that if you want RESTful link, you'll have to edit the Routing config file.
$ajax.get('/controller/action/itemName/itemText/', function(res) {
//do stuff with results... for instance:
res.forEach(function(element) {
$('#someElement').append(element);
});
});
};
And the action:
public JsonResult SearchAction(itemName, itemText) {
List<Item> newItems = items.Where(x => x.ItemName.ToUpperInveriant().Contains(itemName.ToUpperInveriant())
|| x.ItemDescription.ToUpperInveriant().Contains(itemText.ToUpperInveriant())
|| x.ItemPairing.ToUpperInveriant().Contains(itemText.ToUpperInveriant()));
return Json.Encode(newItems.ToArray());
}
Note that I'm not home, so there might be some syntax errors.
Alright, so say I want to return a partial, instead of a simple array:
first, change the action to:
public ActionResult SearchAction(itemName, itemText) {
List<Item> newItems = items.Where(x => x.ItemName.ToUpperInveriant().Contains(itemName.ToUpperInveriant())
|| x.ItemDescription.ToUpperInveriant().Contains(itemText.ToUpperInveriant())
|| x.ItemPairing.ToUpperInveriant().Contains(itemText.ToUpperInveriant()));
return PartialView("~/Views/Partials/MyPartialView.cshtml", newItems);
}
And you create a partial view in the directory you specified, taking the model that you transferred (newItems)
#model IEnumerable<Path.to.Item>
<h3>Results</h3>
<ul>
#foreach(var item in model)
{
<li>#item.Name - #item.Description</li>
}
</ul>
and now when you receive the jquery response:
$.ajax({
type: "POST",
url: "/Items/Search",
data: {ItemName, ItemText},
datatype: "html",
success: function (data) {
$('#result').html(data);
}
});
//since data is the HTML partial itself.
//if you have firebug for Mozilla firefox, you can see what I'm
//talking about
You may want to consider converting both strings to upper or lower, depending on your search requirements. The below code assumes the search is case-insensitive.
public ActionResult Search(string search)
{
string upperSearch = search.ToUpperInvariant();
return View("Index", items.Where(n =>
n.ItemName.ToUpperInvariant().StartsWith(search) ||
n.ItemDescription.ToUpperInvariant().Contains(search)));
}
with the Or condition it will match if either the text or the name matches. If they match different items (like Apple and Tart), you may need to consider what happens in that use-case, but in this case it will return both Apple and Pear.

cannot call json result using jquery

c# and jquery,
I have two drop-down lists(category and product), and have to change the product list based on the category.
#Html.DropDownList("categoryId", new SelectList(ViewBag.Category, "Id", "Name"), "Select Parent Category", new { #class = "form-control categorydata" })
#Html.DropDownList("productId", new SelectList(ViewBag.Product, "Id", "Name"), "Select Product", new { #class = "form-control product-list" })
And i am writing the following controller for getting the products list.It is worked.
[HttpGet]
public JsonResult GetProducts(int categoryId)
{
int tot = new Products().Total;
int cont = 1;
Category cat = new Category(2);
var products = new Products(cont, tot, cat);
// ViewBag.products = new Products(1,new Products().Total,new Category(categoryId));
return Json(products);
}
and my jquery is,
$('.categorydata').change(function () {
var selCat = $(".categorydata").val();
var url = "~/Add/GetProducts";
if (selCat.length != 0) {
$.get(url, { id: SelCat }, function (data) {
alert(data);
});
}
});
This jquery is didn't call the controller, and it can not get the data .
Please help me to solve it.
You should keep the property name in json data as same as the parameter name of the action method.
$.get(url, { categoryId : SelCat }, function (data) {
Refer the SO Post.
You should use this.
return Json(products,System.Web.Mvc.JsonRequestBehavior.AllowGet);
Try to put dataType: 'json' in you ajax call:

Categories

Resources