Confirmation Dialog with Bootstrap/jQuery/ASP.MVC - javascript

I have a simple table with records and each of them has a btn with data-id attribute to run the confirmation dialog:
#foreach (var dog in Model)
{
<tr>
<td>#dog.Name</td>
<td>#dog.Age</td>
<td>Delete</td>
</tr>
}
After clicking the delete btn, this code is running :
$('.deleteBtn').on('click', function () {
$.ajax({
url: '#Url.Action("DeleteConfirm", "Home")',
data: {
id : $(this).attr('data-id')
},
success: function(data)
{
$('#myModal').empty().html(data).modal('show');
}
});
});
As you can see, its Ajax request to my Action in HomeController. It returns PartialView that is loaded to my Bootstrap dialog:
<div class="modal fade" id="myModal">
</div>
After showing the dialog, the user can click confirm to delete the row via button with class saveBtn. Thats what happens after I click it :
$('#myModal').on('click', '.saveBtn', function () {
var numer = $(this).attr('data-id');
$.ajax({
url: '#Url.Action("DeleteDog", "Home")',
type: 'POST',
dataType: 'JSON',
data: {
id: numer
},
success: function (data)
{
if (data = 'true')
$('a[data-id=' + numer + ']').closest('tr').remove();
}
});
});
So as you can see there is another Ajax (POST this time) request to delete the row.
So here is my question. Is this approach good practice? I'm not sure because in order to delete a row i have to send 2 ajax request (to load confirm dialog, and delete after confirm). Can anyone experience developer comment this code and say whether im doing it good or bad? I would be grateful.

It's always a good idea to challenge whether or not you could do things more effectively (as you have here.) So, let's think about it...
The Question:
Is it a good approach to send to two ajax requests - one to load a partial view and the second to post a delete request from the partial - for a single "user action"?
The Answer:
Maybe.
Why?
Based your example, if your goal is to simply confirm with the user whether or not they want to "Delete Dog ID: foo?" You can absolutely do that without making a trip to the server for a partial view. Presumably, in your first ajax call - $(this).attr('data-id'); - is the dog's Id. You already have it!
In most circumstances, when you make a get request with an identifier, like /dogs/id?='foo' you're using foo to access some additional information about the object from a persistent data store. Like, for example, the dog's owners, similar dog breeds, last visit to the vet, etc.
If additional information about the dog (owners, other dogs, vet) is an important part of deciding whether or not to delete the dog AND there's a good reason not to load it when the page loads intially then it totally makes sense to issue two ajax calls.
It could also make sense to issue two ajax calls just to get the partial view html, even if you don't need additional "dog" data, if you simply don't want the "parent" page to be to big (hence, slowing it's loading time.)
Ultimately, though if you're not retrieving additional data, and there's no specific reason to load additional html, it's probably best in this case to just update the modal dialog using javascript/jquery:
Example fiddle

Related

Do a reload of mvc/razor partial view with javascript

In my project I have rows of modules loaded from Partial views.
So imagine a grid of small squares with information.
There is a popup dialog for all of them, that displays the data of the clicked module.
Currently when I submit a change in the dialog, the javascript reloads the entire page. BUT, this takes a long time, and I need to be able to refresh only the one dialog.
I can imagine to make a separate js function for each type of module, and then pass some data in, so jquery can find the specific module, and then make an ajax get, for the data. But this requires me to do all the data insertion from js always. instead of using razor and MVC's built in awesomeness.
Does anyone know of a way, to call a partial view inside a div?
Also in the future I will need to reload "some" but not all the modules in an interval refresh. So for future proofing purposes:
What im looking for is something like:
function reloadElement(row, column, id){
var target = $("#div1");
// todo find row and column
target.html.partial("url", model); //<----- looking for something like this. cross fingers.
}
Thanks to GregH for a few key words, that lead to some ideas.
I solved it myself, so if you land on this problem also, here is how i solved it:
Controller:
You want to make your controller return PartialView("somePartialViewUrl", new SomeModel()), apparently saving the model and relying on the data collection isn't good enough, i hadto make a new instance of the model.
Javascript
in the "click" that handles the event, put:
$.ajax({
url: "controllerName/actionName",
data: JSON.stringify({ row:1,column:2 .... }),
contentType: "application/json",
dataType: "html",
type: "POST",
success: function (partial) {
$("#div2").html(partial);
}
});
this will override the html in your "#div2".
im sure you can also use $("#div2").innerHTML = partial; or $("#div2").load("url",parameters); and probably many other ways.
done.

View response data from AJAX request for multiple elements

I have a like system in my website. Each message has a Like button and a counter next to it.
Now when someone clicks the Like button it should immediately change to 1, and if another user clicks the same message it would change to 2 and so on for each individual message.
I created the AJAX functions required to do this, but I am using document.getElementById which only retrieves the first instance found and views the response from the ajax request.
How can I make it so that it is viewed for each individual message?
Here is my AJAX requests:
jQuery(document).ready(function($){
$('.msg-icon').on('click', function(e){
e.preventDefault();
var reply_id = $(this).find('input[name="replymsg"]').val();
var request = reply(reply_id);
request.done(function() {
checkLikes(reply_id);
});
});
});
function reply(reply_id) {
return $.ajax({
data: reply_id,
type: "post",
url: "replyfavorite.php?replymsg="+reply_id,
});
}
function checkLikes(reply_id) {
return $.ajax({
data: { reply: reply_id },
type: "get",
url: "checkLikes.php?reply=" + reply_id,
success: function(data) {
document.getElementById('likesCount').innerHTML = data; //what can i change here to make the data go to each clicked button?
}
});
}
here is my html button that users click for each message:
<a href="" class="msg-icon" >
<i class="fas fa-heart fa-lg" id="favBtn" style="color: #e74f4e !important;" >
<span id="likesCount"><?php echo $row3['likes_count'] ?>
</span></i></a>
the code is working fine my only problem is with how to let the response go to the clicked message button only.
As you noticed, ID should be unique. Instead of using document.getElementById('likesCount').innerHTML = data;
use the data-* attribute
I.e:
<span data-id="536">12</span>
than inside the jQuery success do like:
success: function(data) {
$(`[data-id="${reply_id}"]`).text(data)
}
and such will update any number of data-id="" elements on the page with the newest likes count.
PS: if you want to make your counts "live" - instead of using AJAX which is one roundtrip-only (request → response), you could use https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API
By using Web Sockets you're making sure an initial handshake is made between any client and your server and than small packets are shared between the two - for multiple clients simultaneously. That way you don't need to have recurring AJAX intervals - and all your guests will see the likes change value "automagically".
Since you are using jquery, why not use $("#likesCount").each(function(){ . . . . .. }); to loop through each item, an inside the each portion you do your ajax request to look for the current value, maybe using $.post() or $.get(), depending on your api.
Update: (Improving my answer)
I understand about the uniqueness of the id of an element in a document.
What I really wanted to say is that you may want change the approach on how to look/search for the details to include inside each span. There you can identify the span objects by grouping them using a Class or a custom attribute, then iterate them using the $.each function. There is no single way to accomplish things, this is just an idea on how to update each element with the correct content.

How to execute JavaScript after dropdown data is inserted via Ajax?

I have a form that loads some of its Data dynamically via Ajax, where, apart of a lot of other stuff, I fill a dropdown list. When selecting an item it will load the corresponding data into a table.
That all works fine, but now I want to be able to, by default, load the data of the first element once the page loads.
But since the dropdown populates over Ajax, it is filled slightly after $(document).ready(), so that doesn't work.
One way it might work would be to just wait for a second or two, since then it should all be loaded, but that really isn't something I fancy doing.
Any idea how I could achieve that?
I already tried it with onloadeddata="loadData($(this)[0].selectedOptions[0].value)" on the select tag, but that doesn't seem to do anything.
EDIT:
And I don't want to execute this in the ajax success function as data might also be loaded in other ways. It should really be the dropdown field or something that watches the dropdown, that executes this.
JQuery Ajax provides a callback for successful request.
$.ajax({
url : 'stackoverflow.com/api',
type: 'GET',
success : successMethod
})
function successMethod(){
// foo
}
Once the request receives a response successMethod will be called.
jquery ajax have a success function in which you can do such kind of functionality. To do so you can try:
success: function(response) {
// fill the form value with 'response'
$('#dropdown_id').val('any_value'); // this will set the dropdown to specific value
}
$.ajax({
url: "test.html",
...
}).done(function(data) {
// do something with your data in here
});

issue using $.ajax with php effectively

I'm having trouble understanding what I'm missing or not doing here (obviously something), and maybe someone can help.
I have a database site that displays a table generated from a SQL database on the client side. When the table is initialized, this code is executed and pulls the data needed for the dropdown in question (comments added by me for this post):
$selectOwner = "SELECT DISTINCT [Contacts].[Alias], [Contacts].[Last Name], [Contacts].[ID] FROM [TechInv].[dbo].[Contacts]";
//this is the file that contains the above query variable
require('custom/Connection.php');
$owner_arr = array();
//$conn is our connection string
$response = sqlsrv_query($conn, $selectOwner);
while ($row = sqlsrv_fetch_array($response)){
array_push($owner_arr, $row['Alias'] . " " . $row['Last Name']);
}
This generates a list of name records pulled from the database in a Alias(first name) Last Name format.
Here's where I'm having trouble
Another function of the site is a menu that allows users of a certain priveledge level to add additional contacts to the table. Everything works fine with that except nowhere in the code is the above array updated when a contact is added, which forces the user to reload the page, ew.
I know i need to use $.ajax for this, so I took a stab at it, and put the following code into the click handler for the 'add contact' submit button:
$.ajax({
type: 'POST',
data: 'listRefresh();',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function() {
alert("this succeeded?");
}
});
The data: 'listRefresh();' line refers to a function I created that is the same as the first block of code, in an attempt to just refresh the variables with new data. That's obviously where I've gone wrong, (try not to laugh) but I am out of ideas here. Can anyone shed some light?
Your ajax call is wrong. The 'data' value is what you send to the server.
Try this:
$.ajax({
type: 'POST',
url: 'wp-content/plugins/editable-grids-api-liam/regenOwnerArr.php',
success: function(data) {
listRefresh(data);
alert("this succeeded?");
}
});
The data variable is what the server gives you back, so you can pass that data to the listRefresh() function and re-render the upated list.
In alternative, you could just reload the page putting location.reload(); into success function

Why is it adding when it’s not being called

I made a JavaScript code that I’m building to make a shopping cart, but this code is run even if I don’t click it:
function addProduct(prodId) {
var sessionDivId = document.getElementById(prodId);
if (prodId) {
sessionDivId.innerHTML = '<?= $_SESSION['product_id_1']+=1 ?>';
}
}
<div onclick="addProduct('testSession1');">ADD</div>
<div id="testSession1"></div>
Everytime I refresh the website it adds 1 to session testSession1 even if I don’t click the button “ADD”.
Your PHP logic will be run on the server before the user loads the page. To add a product, you will need to store it somehwere else (since the PHP has no longer any control to put +=1 to the cart).
I would make an AJAX request to post a product id to the user shopping cart:
function addProduct(prodId) {
// using jQuery for simplicity of writing
$.ajax({
type: "POST",
url: "/cart/item/" + prodId, // or other backend API endpoint
success: displayNiceUserMessage()
});
}
And of course some error handling in case something goes wrong.
Update
I saw that you did not want to use Ajax. Just so you know, it doesn't need to be any more complex than the code I wrote above. Then in the backend you just add +1 to the session if any user makes a POST request to that url.
But if you do not want ajax, you will need to reload the page when clicking the add button. Like was said in the comments, put a form of type post around the add button (and with a good url to make your server know that it was an added item event that took place), and make the add button a submit type. Then no javascript is needed at all.

Categories

Resources