Best strategy to avoid Ajax roundtrips when updating databases in Laravel - ajax

Let's say I have a table with data in the rows coming from a database. On each row of this table there are helper buttons. These buttons perform instant operations on the database, such as setting a status code (for example sold, blocked, in progress), changing an invoice date for the row (for example from 18/11/2022 to null) and so on..
What I would like is that when a user clicks on one of these buttons, an ajax function will performs a request to the related controller that will show a modal box asking for confirmation (not a JS alert but HTML code that comes from a blade component).
So, giving a basic example in the case of the change of status code for the row, what I would do is first set up a route of this type:
Route::post('/status', [TableController::class, 'status']);
after that i will build my controller(using the related model Table) in a way that if the action value coming from the ajax request is confirm(the one coming from the confirmation modal), I will continue with the data update, if instead the action is something different such as status(the one coming from the helper button), then I will bring up my confirmation modal
class TableController extends Controller {
// Change status
public function status(Request $request){
if( $request['action'] == 'confirm' ) {
// Update DB
Table::where('id', $request->id)->update(['status' => 822]);
} else {
$id = $request->id;
// Show confirmation modal
return \Blade::render('<x-confirm :title="$title" :action="$action" :id="$id" />',
[
"title" => "Vuoi bloccare le seguenti disponibilità? ".$id ?,
"action" => "status",
"id" => $id
]);
}
}
If you notice the return of component part here
// Show confirmation modal
return \Blade::render('<x-confirm :title="$title" :action="$action" :id="$id" />'
I'm passing to the component the id of the row, and the action to perform, those datas will be usefull for the next ajax request coming from the confirmation modal, that will update the row in the database. But basically what is happening here?
Send data from frontend to the controller(id of the row, status action, status code).
Send back the same data from the backend to modal component to fill the ajax confirmation request.
Resend back to the server the same data to catch the confirm statement and update the database.
This kind of approach always worked for me, but when things becomes complex(let's say that I have different kind of helpers like I said before, in example remove a date, change the owner, set some flags etc) this will become a mess, because I have everytime to send back the same data that I just received.
So my question:
Is there a way to avoid this thing to sending back and forward those datas? like something in the middle that stores what am I doing in the current session and can inform the modal box without this round trip? Also i am really thinking that my approach is completely wrong and out of mind, so i have to see things from a different point of view? This is because I am self-taught so I certainly have some gaps that I would like to fill.

Related

Inertia.JS reload props after post request

I am currently pretty confused why Inertia.js is not reloading or rerendering my page.
I have a form that could be filled, once submitting this will execute:
Inertia.post("/ban", ban);
This will redirect to a POST in the web.php of my Laravel.
That looks like this:
Route::post("/ban", [Speler::class, "ban"]);
This redirects to a class called "Speler", in there is a function called "ban".
Once done some SQL statements it will execute this return:
return Redirect::route("speler", [$steam])->with("success", "Ban doorgevoerd!");
This will go back to the web.php, and go to the route speler with the session data "success".
That redirect goes into the web.php:
Route::get("/speler/{steam}", [PageLoader::class, "speler"])->name("speler");
This one goes to the PageLoader controller, and execute the "speler" function.
But here it gets weird, this will return a Inertia::render of the same page the person was on, but would need to add another prop, or change the prop. (so i can show a popup with te text that it succeeded)
return Inertia::render("Panel/Speler",
["steamNaam" => $steamNaam, "discord" => $discord, "karakterAantal" => $karakterAantal, "karakters" => $karakters, "sancties" => $sanctiesReturn, "punten" => $aantalPunten, "steamid" => $steamid, "success" => $melding]
);
The "success" prop contains $melding that simply contains a string.
But for some reason it doesn't seem to re-render the page, the form stays filled, and the props are the same.
Does someone have a solution?
If you setup your form with the form helper, you can reset the form on a successful post like this:
form.post('/ban', {
preserveScroll: true,
onSuccess: () => form.reset(), // reset form if everything went OK
})
The success message, which you set with
return Redirect::route("speler", [$steam])->with("success", "Ban doorgevoerd!");
is usually taken care of by the Inertia middleware and made available as 'Shared data'. See this docs page on how to configure that. Shared data is rendered in $page.props variable. That is where you can find the Ban doorgevoerd! message. You can show these to the user as follows:
<div v-if="$page.props.flash.message" class="alert">
{{ $page.props.flash.message }}
</div>
Depending on your implementation, you would need to watch this property. See the FlashMessages component on the pingCRM demo app for an example implementation.

show success message on same page after adding recording without reloadin the site in cakephp 2.x

I want to add a show sucess message using :-
session->flash(); ?> in view and added the message in controller :-
Session->setFlash("Record has been saved successfully."); ?>
But I donot want to reload the whole page.
I am just inserting the new record using ajax.. and refreshing the div having list of all record.
session->flash(); ?> this works if i reload the whole page.
how can I show message once the record is saved using ajax.
Solutions (i recommend the first one):
Create AJAX method in controller that return 200 code with JSON/HTML record's data or any other error code if sth goes wrong. Then in js do:
$.ajax({ ... }).done(function( data ) {
// Success, show the record and message
$('#flash').text('Success!').show();
// ...
}).error( function() {
// Error
$('#flash').text('Error!').show();
});
Refresh the records list by calling ajax method and return not only the view with list of all records, but also a flash message (in the same view). Then show it or move using javascript.

How do I auto fill field values in a section of a form that is loaded via ajax in Laravel 4?

I have a section of a form that dynamically loads different sets of fields based on the user's selection in a control. I'm using a javascript event handler to detect when the selection changes, and using AJAX (with HTML payload) to pull in the proper set of fields.
I would like to be able to use Laravel's Form::getValueAttribute() method to automatically fill in the form fields' values in both the static and dynamic form parts. However, the partial view that is loaded by my AJAX call does not have the same instance of the Form class as the view with my main Form, so I can't simply call getValueAttribute() in the partial.
My thought is to make the AJAX call a POST, and serialize the necessary data (a subset of Input::old() or the model data depending whether the page is loaded as the result of validation errors, or an UPDATE request) to send along with the POST so that the HTML fragment I get back has the values set properly.
Is this the best way to get what I want? If so, does Laravel have any tools to help with the serialization of form data? If not, what might be a better approach?
I've found an approach I like better. When the view is loaded normally I use AJAX as usual to load the partial. But when the view is loaded for a validation post-back or for editing, I use Laravel's Views' nest method to nest the partial view containing the proper fields directly into the response. The partial then has access to all the Input and error data I need. The user is still able to change the field set as usual but I put up a confirm prompt for them if they have already set some values in a field set they previously selected. If they decide to proceed anyway, the field set is cleared and a new field set is brought in via AJAX as usual.
My code looks something like this:
Controller:
public function newThing() {
if ( Request::session()->has('errors') ) {
// this is a validation post-back
return View::make('thing')
->nest('fields', 'fields_partial');
} else {
// just a normal unfilled form
return View::make('thing');
}
}
public function editThing() {
return View::make('thing')
->nest('fields', 'fields_partial');
}
View: thing.blade.php (just a snip of it)
...
<form>
...
<select id="picker">...</select>
<div class="sub-fields">
{{ isset($fields) ? $fields : '' }}
</div>
...
</form>
...
<script>
$('#picker').change(function() {
// if any .sub-fields inputs have been changed, get confirmation from the user
// if user confirms, do ajax stuff to replace .sub-fields contents with new field set
// otherwise cancel the change
});
</script>

how to use last insert id when redirect same form page in codeigniter

I just try to prevent re submission problem when refresh form page. so I use session flashdata() method and redirect same form page. but I want also display recent inputed data on form VIEW page. then I am try $this->db->insert_id() on my form VIEW page . but it always show 0. how can I solve it?
when you redirect the user after the successful form submission then add the parameter in the url just a exapmle with dummy code to make an idea for you
$insertedid=$this->my_model->add_info();
//your add_info() should return the inserted id
redirect("/myformcontroller/myformpage/".$this->db->insert_id());// add id in redirect url
on your myformcontroller controller's myformpage function
function myformpage() {
$insertedid=$this->url->segment(3);
if(!empty($insertedid)){
//get new added information and pass it to view
}
// your other code
}
hope it makes sense

Cakephp 2 render multiple elements from 1 controller function

I call a Js link to update a product status (active/inactive) via ajax
echo $this->Js->link('[X]',
array('action' => 'deactivate', $p['Product']['id']),
array('before'=>$this->Js->get('#loading')->effect('fadeIn'),
'success'=>$this->Js->get('#loading')->effect('fadeOut'),
'update'=> '#'.$divString));
Once the ajax is made, a table row is hidden via the update.
The view is rendered using
$this->render('index_ajax_empty_table_row', 'ajax');
Now i need to update a my menu (via ajax) that holds the categories and counts of active products. So from the same contoller action is am trying
$this->render('index_ajax_menu', 'ajax');
The code will only render the first item or the wrong one in the wrong place.
How do i define multiple success and tell which element to render for each div?

Resources