Laravel Ajax not updating - javascript

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';
}

Related

Laravel cannot retrieve data from multiple model with Ajax

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

WooCommerce Ajax add to cart with additional custom data

I am having some difficulties with trying to add to cart with custom data from the front end.
My current PHP from the backend is as follows - this is placed in my functions.php for my child-theme (This code is from the following post: Adding a product to cart with custom info and price - considering I am indeed a PHP-noobie):
<?php // This captures additional posted information (all sent in one array)
add_filter('woocommerce_add_cart_item_data','wdm_add_item_data',1,10);
function wdm_add_item_data($cart_item_data, $product_id) {
global $woocommerce;
$new_value = array();
$new_value['_custom_options'] = $_POST['custom_options'];
if(empty($cart_item_data)) {
return $new_value;
} else {
return array_merge($cart_item_data, $new_value);
}
}
// This captures the information from the previous function and attaches it to the item.
add_filter('woocommerce_get_cart_item_from_session', 'wdm_get_cart_items_from_session', 1, 3 );
function wdm_get_cart_items_from_session($item,$values,$key) {
if (array_key_exists( '_custom_options', $values ) ) {
$item['_custom_options'] = $values['_custom_options'];
}
return $item;
}
// This displays extra information on basket & checkout from within the added info that was attached to the item.
add_filter('woocommerce_cart_item_name','add_usr_custom_session',1,3);
function add_usr_custom_session($product_name, $values, $cart_item_key ) {
$return_string = $product_name . "<br />" . $values['_custom_options']['description'];// . "<br />" . print_r($values['_custom_options']);
return $return_string;
}
//This adds the information as meta data so that it can be seen as part of the order (to hide any meta data from the customer just start it with an underscore)
add_action('woocommerce_add_order_item_meta','wdm_add_values_to_order_item_meta',1,2);
function wdm_add_values_to_order_item_meta($item_id, $values) {
global $woocommerce,$wpdb;
wc_add_order_item_meta($item_id,'item_details',$values['_custom_options']['description']);
wc_add_order_item_meta($item_id,'customer_image',$values['_custom_options']['another_example_field']);
wc_add_order_item_meta($item_id,'_hidden_field',$values['_custom_options']['hidden_info']);
}
and then I have a button on the frontend that runs the following script when pressed - this runs on a custom wordpress post where I have scripted have done some scripting in the background that collects information based on the users actions on the post:
function cartData() {
var metaData = {
description: 'My test Description'
another_example_field: 'test'
};
var activeVariationId = 10335;
var data = {
action: 'wdm_add_item_data',
product_id: 10324,
"add-to-cart": 10324,
quantity: 1,
variation_id: activeVariationId,
cart_item_data: metaData
};
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.toString().replace( '%%endpoint%%', 'add-to-cart' ),
data: data,
beforeSend: function (response) {
//$thisbutton.removeClass('added').addClass('loading');
},
complete: function (response) {
//$thisbutton.addClass('added').removeClass('loading');
},
success: function (response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
alert('ajax response recieved');
jQuery( document.body ).trigger( 'added_to_cart', [ response.fragments, response.cart_hash ] );
}
},
});
}
Unfortunately this only seems to add my current variation of the product to the to cart without any more custom information. Any help with nesting in this issue would be highly appreciated. If you need any more information and/or code examples I'd be happy to supply it :)
I think that I might have solved it, or at least parts of it with this PHP (this is really just a small modification of this code - adding $cart_item_data https://quadmenu.com/add-to-cart-with-woocommerce-and-ajax-step-by-step/):
add_action('wp_ajax_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_woocommerce_ajax_add_to_cart', 'woocommerce_ajax_add_to_cart');
function woocommerce_ajax_add_to_cart() {
$product_id = apply_filters('woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
$quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
$variation_id = absint($_POST['variation_id']);
// This is where you extra meta-data goes in
$cart_item_data = $_POST['meta'];
$passed_validation = apply_filters('woocommerce_add_to_cart_validation', true, $product_id, $quantity);
$product_status = get_post_status($product_id);
// Remember to add $cart_item_data to WC->cart->add_to_cart
if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id, $cart_item_data) && 'publish' === $product_status) {
do_action('woocommerce_ajax_added_to_cart', $product_id);
if ('yes' === get_option('woocommerce_cart_redirect_after_add')) {
wc_add_to_cart_message(array($product_id => $quantity), true);
}
WC_AJAX :: get_refreshed_fragments();
} else {
$data = array(
'error' => true,
'product_url' => apply_filters('woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));
echo wp_send_json($data);
}
wp_die();
}
Where this is part of the JS-function:
var data = {
action: 'woocommerce_ajax_add_to_cart',
product_id: 10324,
quantity: 1,
variation_id: activeVariationId,
meta: metaData
};
$.ajax({
type: 'post',
url: wc_add_to_cart_params.ajax_url,
data: data, ...........
I am going to have to test it some more, as it seems now that all the data-fields also gets posted in the cart, email etc - I probably have to rewrite something so that some parts of it is hidden for the "non-admin", but available for me later on + adding custom product thumbnail on add to cart.

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 use a javascript onclick event to store information to the database

A customer is logged into the system, they want to book a class through the calendar. Once they click a class to book they are presented with an alert box asking if they would like to book a class. Once they click ok I want this users unique id, and the class to store to the 'class' database table. The code in my classes.php file is:
<script>
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
//set edit to true
//editable:true,
header:{
//what to view
left:'prev,next',
center:'title',
right:''
},
events: 'load.php',
eventClick:function(event)
{
if(confirm("Are you sure you want to book this class?"))
{
var id = event.id;
$.ajax({
url:"book.php",
type:"POST",
data:{title:title, start:start, end:end, thisUser:thisUser},
success:function()
{
calendar.fullCalendar('refetchEvents');
alert("Event Booked");
}
})
}
},
});
});
</script>
The code to book the class in the 'book.php' file is:
if(isset($_POST["title"]))
{
$query = "
INSERT INTO class
(title, start_event, end_event, cust_id)
VALUES (:title, :start_event, :end_event, :thisUser)
";
$statement = $connect->prepare($query);
$statement->execute(
array(
':title' => $_POST['title'],
':start_event' => $_POST['start'],
':end_event' => $_POST['end'],
':cust_id' => $_POST['thisUser']
)
);
}
I can't get anything to store in my database.

How to add an AJAX action - Elgg

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);
});
}

Categories

Resources