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.
Related
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
From my console output, I can see that the success message has been displayed from the controller method that ajax called, but i have no idea why the value in db is not changing according to the value.
this is my html code
#foreach($system_functions as $function)
<input type="hidden" id="id" value="{{$function->id}}" />
#if($function->group_id == 1)
<tr>
<td>{!! $function->name !!}</td>
<td><input class="toggle_status" type="checkbox" #if($function->is_active) checked #endif id="is_active" name="is_active" data-on="启用" data-off="禁用" value="on" data-toggle="toggle"></td>
</tr>
#endif
#endforeach
my ajax in the same file
#section('script')
<script type="text/javascript">
$(document).ready(function() {
$('.toggle_status').change(function (e) {
e.preventDefault();
var is_active = 0
if ($(this).is(':checked')) {
is_active = 1;
}
$.ajax({
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '/admin/system-functions',
async: true,
data: {
is_active: is_active,
id: {{ $function->id }}
},
success: function (data) {
$.confirm({
title:'edit?',
content:'confirm to edit?',
buttons:{
confirm: {
text: 'edit',
btnClass: 'btn-danger',
action: function () {
}
},
cancel: {
text: 'cancel',
btnClass: 'btn-default',
action: function () {
}
}
}
});
}
});
});
});
</script>
#endsection
this is my method in controller
public function update(Request $request)
{
$id = Input::get('id');
$function=SystemFunction::where('id',$id)->first();
if($request->get('is_active')==='on'){
$is_active=1;
} else{
$is_active=0;
}
$function->update([
'is_active' => $is_active
]); return response()->json(['success' => 'successful']);
}
this is my route
Route::post('/system-functions', 'SystemFunctionController#update');
this is my modal class
class SystemFunction extends Model
{
protected $fillable=['name','group_id','is_active'];
static function isFunctionActive($function_name){
$function=SystemFunction::whereName($function_name)->first();
if(!$function){
return false;
}
return $function->is_active==true;
}
}
try this :
public function update(Request $request) {
$id = Input::get('id');
if($request->get('is_active')==='on'){
$is_active=1;
} else {
$is_active=0;
}
$function=SystemFunction::where('id',$id)->update([
'is_active' => $is_active
]);
return response()->json(['success' => 'successful']);
}
hopefully that can help
Try this, if DB doesn't get updated then you can track it through error messages:
try {
$id = Input::get('id');
$is_active = empty(Input::get('is_active')) ? 0 : 1;
$function = SystemFunction::findOrFail($id)->update(['is_active' => $is_active]);
if ($function) {
return response()->json(['success' => 'successful'], 200);
}
$error = ['errors' => ['message' => 'no data']];
return response()->json($error, 204);
} catch (Exceptoin $e) {
$error = ['errors' => ['message' => $e->getMessage()]];
return response()->json($error, 200);
}
I have Laravel project for fire department and I have competitions with results of each team. I made a page where I can edit competition. In result controller
public function update (Request $request){
$item = new Items();
$item->item = $request->item;
$item->data = $request->data;
$item->miejscowosc = $request->miejscowosc;
$item->gmina = $request->gmina;
$item->wojewodztwo = $request->wojewodztwo;
$item->poziom = $request->poziom;
$item->komisja1 = $request->komisja1;
$item->komisja2 = $request->komisja2;
$item->komisja3 = $request->komisja3;
$item->komisja4 = $request->komisja4;
$item->komisja5 = $request->komisja5;
$item->sedzia_glowny = $request->sedzia_glowny;
$item->komisje_powolal = $request->komisje_powolal;
$item->protesty = $request->protesty;
$item->kontuzje = $request->kontuzje;
$item->uwagi = $request->uwagi;
$item->update();
return 'Done';
}
When I change :
$item->update();
To :
$item->save();
It perfectly adds new competition. But when I have
$item->update();
It doesn't update.
Here is my ajax code :
$(document).ready(function() {
$('#updateComp').click(function (event){
$.ajax({
type: 'post',
url: '',
data: {
'_token': $('input[name=_token]').val(),
'item': $("#item").val(),
'data': $('#data').val(),
'miejscowosc': $('#miejscowosc').val(),
'gmina': $('#gmina').val(),
'wojewodztwo': $('#wojewodztwo').val(),
'poziom': $('#poziom :selected').text(),
'komisja1': $('#komisja1').val(),
'komisja2': $('#komisja2').val(),
'komisja3': $('#komisja3').val(),
'komisja4': $('#komisja4').val(),
'komisja5': $('#komisja5').val(),
'sedzia_glowny': $('#sedzia_glowny').val(),
'komisje_powolal': $('#komisje_powolal').val(),
'protesty': $('#protesty').val(),
'kontuzje': $('#kontuzje').val(),
'uwagi': $('#uwagi').val()
},
success: function(data){$('#alert').append('<div class="alert alert-success">Dodano do bazy</div>')},
error: function(){$('#alert').html('<div class="alert alert-danger">Błąd, nie udało się dodać do bazy. Wprowadź dane ponownie</div>')}
});
});
Do I have to change something in ajax code to make it work? Or is it another reason?
(really sorry for other language in project)
For eloquent update, change your code like below code:
Items::find($id)->update(['column' => 'value']);
Here $id is id which you want to update the record. See document
UPDATE
$id = $request->id;//Item id to update...
$arrItem = array(
'item' => $request->item,
'data' => $request->data,
.
.
.
'uwagi' => $request->uwagi,
);
//Update item data...
Items::find($id)->update($arrItem);
you have to send the item id to, so it can point which item need to update
$.ajax({
type: 'post',
url: 'your_url',
data: {
'id':$('#your_id_field'),
'your other field':$('#your_other_field),
.
.
},
success: function(data){$('#alert').append('<div class="alert alert-success">Dodano do bazy</div>')},
error: function(){$('#alert').html('<div class="alert alert-danger">Błąd, nie udało się dodać do bazy. Wprowadź dane ponownie</div>')}
});
//controller, find the data using items model by searching the item's id
public function update (Request $request){
$item = Items::find($request->get('id'));
$item->item = $request->get('item');
.....
.....
....
$item->update();
return 'Done';
}
I'm trying to create an AJAX action in elgg. I have followed this Elgg tutorial: Ajax: Performing actions, but I'm getting nothing so far, apart from the fail error:
Sorry, Ajax only!
The other error is that the page reloads, instead of persisting the data asynchronously.
What am I getting wrong? Thank you all in advance.
Below is my code:
form: views/default/forms/service_comments/add.php
<?php
$url_confirm = elgg_add_action_tokens_to_url("action/service_comments/add?guid={$guid}");
$params_confirm = array(
'href' => $url_confirm,
'text' => elgg_view_icon('upload'),
'is_action' => true,
'is_trusted' => true,
'class' => 'upload-media-update',
);
$confirm = elgg_view('output/url', $params_confirm);
?>
<div class="update-options">
<?= $confirm ?>
</div>
start.php
elgg_register_action("service_comments/add", __DIR__ . "/actions/service_comments/add.php");
action file: actions/service_comments/add.php
<?php
elgg_ajax_gatekeeper();
$arg1 = (int)get_input('arg1');
$arg2 = (int)get_input('arg2');
// will be rendered client-side
system_message('We did it!');
echo json_encode([
'sum' => $arg1 + $arg2,
'product' => $arg1 * $arg2,
]);
Javascript : views/js/service_comments/add.js
var Ajax = require('elgg/Ajax');
var ajax = new Ajax();
ajax.action('service_comments/add', {
data: {
arg1: 1,
arg2: 2
},
}).done(function (output, statusText, jqXHR) {
if (jqXHR.AjaxData.status == -1) {
return;
}
alert(output.sum);
alert(output.product);
});
You have written ajax procedure but not invoking it. Instead you are directly calling it . by making it link.
$params_confirm = array(
'href' => '#',
'text' => elgg_view_icon('upload'),
'onclick' => "myajax_function()",
'class' => 'upload-media-update',
);
$confirm = elgg_view('output/url', $params_confirm);
Then move your JS code inside a function.
function myajax_function(){
var Ajax = require('elgg/Ajax');
var ajax = new Ajax();
ajax.action('service_comments/add', {
data: {
arg1: 1,
arg2: 2
},
}).done(function (output, statusText, jqXHR) {
if (jqXHR.AjaxData.status == -1) {
return;
}
alert(output.sum);
alert(output.product);
});
}
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();
}