I have a personnel table in a database with a unique id (p_id) for each person.
Then there are 2 other tables(authorisations and interventions) with records linked to the personnel table with (p_id)
So i need to delete person from the database, I pass/send p_id to a delete function in the controller to delete the person, but i need to check that no records exists in the authorisations and interventions tables before the person can be deleted.
i use form_validation on p_id
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('','');
$this->form_validation->set_rules(
'p_id', 'Autorisations', array(
'trim', array(
'p_id_auth_callable',array($this->Personnel_model, 'check_pers_tasks')
)
),
array('p_id_auth_callable' => ' Delete All {field}')
);
$this->form_validation->set_rules(
'p_id', 'Interventions', array(
'trim', array('p_id_intv_callable',array($this->Personnel_model, 'check_pers_intv'))
),
array('p_id_intv_callable' => ' Delete All {field}')
);
if ($this->form_validation->run() == FALSE){
$pers_delete_msg['icon'] = 'fas fa-exclamation-triangle fa-lg';
$pers_delete_msg['title'] = 'Warning';
$pers_delete_msg['status'] = 'warning';
$pers_delete_msg['text'] = validation_errors('<span class="fas fa-exclamation-triangle"></span>','');// . print_r($post_val,true) ;
}
else{
//delete person
}
both these rules work (if i use one of them) i get the correct message.
If i use both rules together like the code above only the message from the last rule is generated.
Can i have 2 callables in one rule combined.
I use a datatable plugin and send the p_id via jquery ajax function to the controller
$('#table tbody').on( 'click', '.delete_pers', function (e) {
e.preventDefault();
var pers_data = table.row( $(this).parents('tr') ).data();
$.ajax({
url: base_url +"personnel/delete_pers/",
data: {
p_id: pers_data['p_id']
},
type: 'POST',
dataType:'json',
success: function(response){
//display response
}
error: function(response){
//display
}
} );
Related
Adding an item takes eight clicks, in the WC admin order page, so I thought I would add custom buttons for some of my most commonly-added products to do it all at once. I found several hints that get me most of the way there -- the item is indeed added to the order, but it doesn't appear until you reload the page, or hit Recalculate. Calling $('.calculate-action').trigger('click'); at that point does work but that requires yet another click ("OK"), an annoyance I am trying to avoid. The regular "Add Item(s)" and then "Add products" ... "Add" (with all the faffing about to select the product) just gets on with it at this point. How?
Is there a different approach, or maybe one more call I need to add?
scna_orderadmin_add_product.js:
(function( $ ) {
'use strict';
$('.inside').on('click','#scna_item_button', function(){
// get the order_id from the button tag
var order_id = $(this).data('order_id');
// get the product_id from the button tag
var product_id = $(this).data('product_id');
// send the data via ajax to the sever
$.ajax({
type: 'POST',
url: mb_script_var.ajaxurl,
dataType: 'json',
data: {
action: 'scna_orderadmin_add_product',
order_id: order_id,
product_id: product_id
},
success: function (data, textStatus, XMLHttpRequest) {
// if(data.error == 0)
// {
// trigger the "Recalculate" button to recalculate the order price
// and to show the new product in the item list
// $('.calculate-action').trigger('click');
// }
// show the control message
alert(data.msg);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
})( jQuery );
functions.php:
/** Add a custom button to the admin order page to add SCNA Membership.
*
* To save clicks when creating a new order from a paper form.
*/
function scna_orderadmin_add_product_buttons($order)
{
// Add a button that adds SCNA 1- and 2-year memberships, to save steps.
// the button tag gets as data attributes your product id and the order id
// later we will grab this data and send them to the server
echo '<button id="scna_item_button" type="button" class="button add-special-item" data-order_id="'. esc_attr($order->get_id()) .'" data-product_id="112" >Add SCNA 1-year</button>';
echo '<button id="scna_item_button" type="button" class="button add-special-item" data-order_id="'. esc_attr($order->get_id()) .'" data-product_id="113" >Add SCNA 2-year</button>';
}
/**
* hook to add the button
*/
add_action('woocommerce_order_item_add_action_buttons', 'scna_orderadmin_add_product_buttons');
/**
* Add javascript
*/
function scna_orderadmin_add_product_js_file()
{
wp_enqueue_script( 'scna_orderadmin_add_product_js', get_stylesheet_directory_uri() ."/js/scna_orderadmin_add_product.js", array('jquery'), NULL, true );
// send the admin ajax url to the script
wp_localize_script( 'scna_orderadmin_add_product_js', 'mb_script_var', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
}
/**
* hook to add the javascript file
*/
add_action( 'admin_enqueue_scripts', 'scna_orderadmin_add_product_js_file' );
/**
* Ajax callback
*/
function scna_orderadmin_add_product()
{
/////////////////////////////////////////////////////////////////////////////
/// Attention, to keep the example simple we will not check any ajax data. //
/////////////////////////////////////////////////////////////////////////////
//
// the data from the ajax call
$order_id = intval($_POST['order_id']);
$product_id = intval($_POST['product_id']);
//getting order Object
$order = wc_get_order($order_id);
// gettting the product
$product = wc_get_product($product_id);
$back_data = array('error' => 0, 'msg' => '');
if($order !== false AND $product !== false)
{
// Add the product to the order
$order->add_product($product, 1);
// Save the order data
$order->calculate_totals();
//$order->save();
$back_data['msg'] = 'The item was added';
}
else
{
$back_data['error'] = 1;
$back_data['msg'] = 'No item was added';
}
wp_send_json( $msg );
}
/**
* hook to add the ajax callback
*/
add_action( 'wp_ajax_scna_orderadmin_add_product', 'scna_orderadmin_add_product' );
Hello every one I'm using laravel8 and using Ajax to insert records in database.
my problem is that after I insert record ,then it automatically goes to new page but it just contains an response as json object(screenshot of page below)
How can I prevent that and redirect in normal way.
my controller code :
public function store(Request $request){
$user = User::create($request->all());
return response()->json(['url'=>url('/users')]);
}
my view :
$.ajax({
type: "POST",
url: "{{route('users.store')}}",
data:{
name: $("#name").val(),
email : $("#email").val(),
image : $("#image").val(),
},
success: function(response){
if(response){
$("#userTable tbody").prepend(
'<tr><td>'+ response.id+'</td><td>'
+ response.name+'</td><td>',
+ response.email+'</td><td>',
+ response.image+'</td><td>'
)
window.location.href=response.url;
$("#userForm")[0].reset();
$("#userModel").model('hide');
}
here is the page
sorry for my bad english
The problem is here return response()->json(['url'=>url('/users')]);
You can just return per example return response()->json(data);
Here's an example :
Controller :
public function store(Request $request){
$user = User::create($request->all());
$data = collect();
//TODO: find a way to catch user data you created
$data->push([
'email' => (your attribute),
'name' => (your attribute),
'image' => (your attribute),
'id' => (your attribute),
'url' => (your url),
]);
return response()->json($data);
}
Ajax :
$.ajax({
type: "POST",
url: "{{route('users.store')}}",
data:{
name: $("#name").val(),
email : $("#email").val(),
image : $("#image").val(),
},
success: function(data){
if(data){
$("#userTable tbody").prepend(
'<tr><td>'+ data.id+'</td><td>'
+ data.name+'</td><td>',
+ data.email+'</td><td>',
+ data.image+'</td><td>'
)
window.location.href=data.url;
$("#userForm")[0].reset();
$("#userModel").model('hide');
}
I have a list of hotels in a select I want update the database base on the hotel selected if it update the field I want to alert it on the home page.
this is the ajax function
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'{{ route('home', '') }}/'+id,
data:{_token:'{{ csrf_token() }}'},
success:function(data){
alert(data);
},
error: function (result) {
alert("Error occur in the update()");
}
});
}
}
my controller
public function update(Request $request, $hotel_plan_id)
{
$hotel=plan_hotel::where('hotel_plan_id', $hotel_plan_id)->first();
$hotel->hotel_name = $request->input('hotel_name');
//$hotel ->room_name = $request->input('room_name');
$hotel->save();
// return redirect('/home')->with('success', 'price updated');
}
my route
Route::post('home/{hotel_plan_id}', 'HomeController#update')->name('home');
my select form
{!! Form::select('hotel_name', array($item[4], $item[10]),'S', array('style'=>' Border:none; ', 'id' => 'hotel_id', 'onclick'=>"showRoom(this.value, $item[8])"));!!}
You have error with ajax url and you dont also pass the value of hotel name.
Check this changes.
function showRoom($hotel_plan_id) {
var id = $hotel_plan_id;
if (id !== "") {
$.ajax({
type: "POST",
dataType: 'JSON',
url:'/home/' + id,
data:{_token:'{{ csrf_token() }}', hotel_name: 'Your value here'},
});
}
Please return json response
return response()->json();
You have to return json object like this
return response->json([
'status' => 200,
'result' => true,
'error' => false,
'data' => $hotel
]);
i want to set condition, if teacher already exist in database then update record, if id doesn't exist then add record in database. how can i achieve it using ajax in laravel?
Update.js:
jQuery(document).ready(function($) {
$('#update-data').on('click',function(){
alert("ok");
$.ajax({
type: "POST",
url: "teachers/" + $('#update-data').attr("value"),
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
beforeSend: function() {
},
success: function (data) {
alert("ok");
},
});
});
});
Store.Js:
jQuery(document).ready(function($) {
$("#add-data").submit(function (e) {
$.ajax({
type: "POST",
url: "teachers",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: $(this).serialize(),
success: function (data) {
alert("Added");
data.responseJSON;
refreshTable();
},
});
});
});
Update Controller:
public function update(TeacherRequest $request, $id)
{
$teacher = Teacher::find($id);
if($teacher->save()){
return response()->json([
'status' => 'success',
'msg' => 'esecond has been updated'
]);
}
}
Store Controller:
public function store(Request $request)
{
$teacher = new Teacher;
$teacher=teacher::create($request);
}
There's a custom method for this
$teacher = Teacher::firstOrCreate($id, [
// Pass data here
]);
And if you want to check manually and traverse the request to another method
public function update(TeacherRequest $request, $id)
{
$teacher = Teacher::find($id);
if (is_null($teacher)) { // If model not found, pass request to store method
$this->store($request);
}
if($teacher->save()){
return response()->json([
'status' => 'success',
'msg' => 'esecond has been updated'
]);
}
}
From the docs
Hope this helps
Eloquent provides a updateOrCreate method so you can update or create a record.
$teacher = Teacher::updateOrCreate([
// attributes to search for
'name' => 'Test Teacher',
], [
// values
'grade' => 6,
]);
This would find a teacher with name 'Test Teacher' and update grade to 6 or create a new teacher with name 'Test Teacher' and grade set to 6.
"You may also come across situations where you want to update an existing model or create a new model if none exists. Laravel provides an updateOrCreate method to do this in one step. Like the firstOrCreate method, updateOrCreate persists the model ..." - Laravel 6.0 Docs - Eloquent - Other Creation Methods - updateOrCreate
I think this is a simple one.
I have a Codeigniter function which takes the inputs from a form and inserts them into a database. I want to Ajaxify the process. At the moment the first line of the function gets the id field from the form - I need to change this to get the id field from the Ajax post (which references a hidden field in the form containing the necessary value) instead. How do I do this please?
My Codeigniter Controller function
function add()
{
$product = $this->products_model->get($this->input->post('id'));
$insert = array(
'id' => $this->input->post('id'),
'qty' => 1,
'price' => $product->price,
'size' => $product->size,
'name' => $product->name
);
$this->cart->insert($insert);
redirect('home');
}
And the jQuery Ajax function
$("#form").submit(function(){
var dataString = $("input#id")
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/home/add",
data: dataString,
success: function() {
}
});
return false;
});
As always, many thanks in advance.
$("#form").submit(function(){
var dataString = $("input#id")
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/home/add",
data: {id: $("input#id").val()},
success: function() {
}
});
return false;
});
Notice data option in the ajax method. Now you could use $this->input->post('id') like you are doing in the controller method.
Why not slam it to the end of
url: "/home/add",
like
url: "/home/add/" + $("input#id").val(),
Then I guess codeigniter will treat it like a normal parameter ... ?