Do AJAX check before confirming delete - javascript

I have a Telerik grid. For the uninitiated, it just means I've got a table on a page.
On this Telerik grid, I've got a column for deleting a record. I originally had it so that a user could click, and then it would fire a javascript confirm dialog. If the user hit ok, it would call go the Delete link; if not then it would cancel without refreshing the page. That original code is below.
columns.Template(
#<text><a href='#Url.Content("~/HazardControl/Delete/" + #item.Id)'
style="cursor:pointer;" onclick = "return confirm('Are you sure you want to delete this record?');">
<img src="~/Content/Images/DeleteItem.gif" alt="Delete" />
</a></text>
).Width(50).HtmlAttributes(new { style = "text-align:center" });
Now, the requirements I have now is that they want to check if a record is eligible for deletion before doing that confirm delete, so now my code looks like this:
columns.Template(
#<text><a href='#Url.Content("~/Training/Delete/" + #item.Id)'
style="cursor:pointer;" onclick="deleteConfirmation(#item.Id)">
<img src="~/Content/Images/DeleteItem.gif" alt="Delete" />
</a></text>
).Width(50).HtmlAttributes(new { style = "text-align:center" });
<script type="text/javascript" >
function deleteConfirmation(recordId) {
$.ajax({
url: '#Url.Action("ValidateDelete", "Training")',
type: 'POST',
data: { id: recordId },
success: function (result) {
var deleteRecord = false;
if (result) {
var userConfirm = confirm('Are you sure you want to delete this record?')
if (userConfirm) {
deleteRecord = true;
}
}
else {
alert('Delete no allowed, the record is in use!');
}
return deleteRecord;
}
});
return false;
}
</script>
I thought I'd be able to accomplish this by using an AJAX call before doing the confirm, BUT what actually happens is that the validation part occurs correctly, then the link activates anyway despite returning false or true. I though that when you used the anchor tag and used the onclick method and returned false, then the nothing would happen, but that does not seem to be the case when using AJAX. What am I doing wrong here? Has this been done before? Is it possible here?

The AJAX call occurs asynchronously so returning true or false will have no effect on the event bubbling.
In my example below if it returns true it will trigger a click of the original element that will this time return true and allow the link click to go through. The variable deleteRecord might have to be renamed if you have multiple links and the #linkid should be for the element that was originally clicked. If you assigned an id to the link of deleteItem-#item.Id you could pick this up in the JavaScript.
var deleteRecord = false;
function deleteConfirmation(recordId) {
if(!deleteRecord)
{
$.ajax({
url: '#Url.Action("ValidateDelete", "Training")',
type: 'POST',
data: { id: recordId },
success: function (result) {
if (result) {
var userConfirm = confirm('Are you sure you want to delete this record?')
if (userConfirm) {
deleteRecord = true;
$("#linkid").click();
}
}
else {
alert('Delete not allowed, the record is in use!');
}
}
});
}
return deleteRecord;
}

Here's how I did it: Removed the link and gave the OnClick event to the image. Javascript to do the checks and calls to Delete link.
columns.Template(
#<text>
<img src="~/Content/Images/DeleteItem.gif" alt="Delete" style="cursor:pointer;" onclick="deleteConfirmation(#item.Id)" />
</text>
).Width(50).HtmlAttributes(new { style = "text-align:center" });
<script type="text/javascript">
function deleteConfirmation(recordId) {
$.ajax({
url: '#Url.Action("ValidateDelete")',
type: 'GET',
data: { id: recordId },
success: function (result) {
if (result) {
var userConfirm = confirm('Are you sure you want to delete this record?')
if (userConfirm) {
window.location.href = '#HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString()/Delete/' + recordId;
}
}
else {
alert('Delete not allowed, the record is in use!');
}
}
});
}
</script>

Related

CRUD - Add and Delete not working one after other if page is not refreshed

I have one annoying problem that I am not able to solve.
I am generating CRUD operations in my Symfony project. I made an AJAX request for Add method which works as it should.
After that I have created AJAX request for Delete method.
When I add my new entity object the table is reloaded without page refresh.
Problem is that if I click delete after it's added it throws an error that ID is not found.
/**
* #Route("/user/{id}", name="user_delete", options={"expose"=true})
*/
public function delete($id)
{
$em = $this->getDoctrine()->getManager();
$$user = $em->getRepository(User::class)
->findOneby(['id' => $id]);
if (!$user) {
throw $this->createNotFoundException('No User found for id '.$id);
}
$em->remove($user);
$em->flush();
return $this->json(["message" => "SUCCESS"]);
}
So, for example I have added entity with ID = 2 . DIV is reloaded. Now I click in delete of 2 and it's says:
No user found for id 1
Problem is it always fatches the last ID I deleted after page refresh.
Now, if I refresh the page and then try delete it will catch ID = 2 and delete it. Now, I add ID = 3 without refreshing the page and it will throw:
No user found for id 2
I think maybe it has to do with my add form:
Add form:
$('#form-submit').on('click', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '/subscription/add',
data: $('form#subscription-form').serialize(),
processData: false,
success: function () {
$("#user-table").load(location.href + " #user-table");
$('#addUser').modal('hide');
displayNotif('success', 'check', 'User created successfully');
},
error: function (xhr, status, error) {
var ErrorMessage = JSON.parse(xhr.responseText);
$('#general-error').html(ErrorMessage.message);
}
});
});
Can someone please help?
$(document).ready(function () {
$('.user_delete').on('click', function () {
let removeUrl = $(this).attr('data-remove-url');
$('.remove-user').attr('data-remove-url', removeUrl);
});
$(".remove-user").click(function (e) {
let removeUrl = $(this).attr('data-remove-url');
e.preventDefault();
$.ajax({
url: removeUrl,
type: 'DELETE',
success: function()
{
$("#user-table").load(location.href + " #user-table");
$('#confirmDelete').modal('hide');
displayNotif("danger", "warning", "User deleted successfully");
}
});
});
});
I am adding everything so you can get an idea of what I am doing:
<a href data-toggle="modal" data-target="#confirmDelete" data-remove-url="{{ path('user_delete', {'id':user.id}) }}" class="btn user_delete">x</a>
Option 1:
The click event is not working properly for the delete button.
Try to replace
$(".remove-user").click
With
$(".remove-user").on(“click”
Option 2:
data-remove-url
this attribute is not updated accordingly. Check your DOM to verify

Redirect to another page after Ajax call?

so this is a hard one for me to try and explain. I have a razor page that when a button is clicked it calls a javascript function which makes an ajax call to a handler in the back end. The handler does some stuff and gets a id that I want to pass to another page. I am trying to use the RedirectToPage function in the back end but the screen never opens. It successfully calls the handler but when the handler does its return, nothing happens. Is there a way to do this?
Here is the javascript/ajax code that gets called from a button being clicked.
#section scripts{
<script>
// Get the account ID Data from the row selected and return that to the program.
function getIDData(el) {
var ID = $(el).closest('tr').children('td:first').text();
var iddata = {
'ID': ID
}
console.log(iddata);
return iddata;
}
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var accountid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
            xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
        },
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
},
});
});
</script>
}
For my code behind code that I am calling from the ajax call, that's below here:
public ActionResult OnPostCopyData (string accountid)
{
// Do my other stuff here
return RedirectToPage("Account_Information", new { id = account.Account_ID });
}
Any help would be appreciated and if doesn't make sense, I can try and clear up any questions.
I think this is what you want, I did something similar in an MVC 5 project and I haven't tested it in Razor Pages yet:
This would be your method, note that you should add your Controller to the Url.Action, and I personally haven't tried passing a parameter along with the url but I image it'll work just fine
[HttpPost]
public ActionResult SubmitSomething()
{
return Json(new { redirectUrl = Url.Action("Account_Information", "YOUR_CONTROLLER_NAME", new { id = account.Account_ID }) });
}
And then this would be your Ajax request, I updated the success portion
// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
var accountid = JSON.stringify(getIDData(this));
$.ajax({
url: '/Copy_Old_Account?handler=CopyData',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
type: 'POST',
dataType: 'json',
data: { offenderid: offenderid },
success: function (result) {
if (result.redirectUrl !== undefined) {
window.location.replace(result.redirectUrl);
} else {
// No redirect found, do something else
}
},
});
});
This isn't tested, so I can only hope that it works for you right now
Edit: Updated the Url.Action to use OP's view names and parameters
Redirect to page returns a 301 response, which will be in the format:
HTTP/1.1 301 Moved Permanently
Location: http://www.example.org/index.asp
To redirect after the ajax call you can redirect to the requested url by:
success: function (result) {
window.location = result.getResponseHeader('Location');
}

ASP.net/JS/JQuery/AJAX - ajax works but handler event not firing properly

I have a HTTP handler (ASHX) which I am calling from UI side using an AJAX function. The following is what needs to happen in this call:
When the section loads, it will display the status of the short code on the server in the shortcodestatus span. It will either say on or off:
<a class="btn btn-default" id="toggleshortcode">Short Code <span id="shortcodestatus"></span></a>
This is the function for getting the status of the short code and this works properly. I can manually change the status of the short code and the changes reflect properly on the div when I reload the page:
function ShortCodeStatus() {
$.ajax({
type: "GET",
url: "Handler.ashx?action=shortcodestatus",
success: function (output) {
console.log("getShortCodeStatus: " + output);
$("#shortcodestatus").empty();
if (output == "true") {
$("#shortcodestatus").text("ON");
$("#shortcodestatus").addClass("btn btn-success");
}
else {
$("#shortcodestatus").text("OFF");
$("#shortcodestatus").addClass("btn btn-danger");
}
}
});
};
This is the short code status code from the handler:
case "shortcodestatus":
{
output = ShortCodeStatus() ? "true" : "false";
}
break;
I want to be able to click on the toggleshortcode div to fire off this event through the handler. The functions for disabling and enabling the short code are working properly:
case "toggleshortcode":
{
if (ShortCodeStatus() == true)
{
DisableShortCode();
output = "false";
}
else
{
EnableShortCode();
output = "true";
}
}
break;
Here is the ajax call for the short code toggle:
$('#toggleshortcode').click(function () {
$.ajax({
type: "POST",
url: "Handler.ashx?action=toggleshortcode",
success: function (output) {
console.log("toggleshortcode: " + output);
ShortCodeStatus();
}
});
});
I'm hitting the URLs correctly and I'm getting the correct responses from each function. However the change to the short code does not seem to be happening.
For example, if the short code is off, the ShortCodeStatus function will return false and thus render the OFF button. When I click on the toggleshortcode button, the output is true (I want to turn on short code) which is correct but when the ShortCodeStatus function fires again in the success, it will still say false. The ajax functions seem correct but I can't figure out why the toggleshortcode on the handler is not firing properly.
Thank you so much for your time!
I'm seeing 2 cases that you can check.
First, in the ajax call for 'toggleshortcode', you are calling the function 'getShortCodeStatus()', and base on your example the correct name of the function is 'ShortCodeStatus()'.
Second, in the call to 'Handler.ashx?action=toggleshortcode', you are already returning the status (true or false), I suggest you make a javascript function named SetShortCodeStatus(status) , and use this inside of the success of both ajax request 'Handler.ashx?action=shortcodestatus' and 'Handler.ashx?action=toggleshortcode'.
function SetShortCodeStatus(status) {
$("#shortcodestatus").empty();
if (status == "true") {
$("#shortcodestatus").text("ON");
$("#shortcodestatus").addClass("btn btn-success");
}
else {
$("#shortcodestatus").text("OFF");
$("#shortcodestatus").addClass("btn btn-danger");
}
}
function ShortCodeStatus() {
$.ajax({
type: "GET",
url: "Handler.ashx?action=shortcodestatus",
success: function (output) {
console.log("getShortCodeStatus: " + output);
SetShortCodeStatus(output);
}
});
};
$('#toggleshortcode').click(function () {
$.ajax({
type: "POST",
url: "Handler.ashx?action=toggleshortcode",
success: function (output) {
console.log("toggleshortcode: " + output);
SetShortCodeStatus(output);
}
});
});

submit form with ajax validation jquery / standard javascript

I'll start with an apology - I'm a .NET coder with little (no) front-end experience.
When the user clicks on Submit, the form needs to call a REST service, if the service returns true then the user is presented with a warning that a duplicate exists and are asked whether they want to continue. Appreciate any help.
I have the Submit button ONCLICK wired up to Approve()
When the checkForDuplicateInvoice() gets called, it passes the control back to the calling function right away before the ajax call has a chance to get the result. The effect is that the Validate() function finishes without taking into account whether or not a duplicate invoice exists.
I need help in modifying the form so that when the user clicks on the submit button, the form validates (including the ajax call to the db) before finally submitting.
I've modified the code based on Jasen's feedback.
I'm including https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js in my header.
The error I get now is "Object doesn't support property or method 'button'"
What I have now for my form submission/validation is:
$(document).ready(function () {
$("#process").button().click( function () {
if (ValidateFields()) { // internal validation
var companyCode = document.getElementById("_1_1_21_1").value;
var invoiceNo = document.getElementById("_1_1_25_1").value;
var vendorNo = document.getElementById("_1_1_24_1").value;
if (vendorNo == "undefined" || invoiceNo == "undefined" || companyCode == "undefined") {
return false;
}
$.ajax({ // external validation
type: "GET",
contentType: "application/json;charset=utf-8",
//context: $form,
async: false,
dataType: "jsonp",
crossDomain: true,
cache: true,
url: "http://cdmstage.domain.com/services/rest/restservice.svc/CheckDuplicateInvoice?InvoiceNumber=" + invoiceNo + "&VendorNumber=" + vendorNo + "&CompanyCode=" + companyCode,
success: function (data) {
var result = data;
var exists = result.CheckForInvoiceDuplicateResult.InvoiceExists;
var valid = false;
if (exists) {
if (confirm('Duplicate Invoice Found! Click OK to override or Cancel to return to the form.')) {
valid = true;
}
}
else {
valid = true; // no duplicate found - form is valid
}
if (valid) {
document.getElementById("_1_1_20_1").value = "Approve";
doFormSubmit(document.myForm);
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
});
});
First review How do I return the response from an asynchronous call? Understand why you can't return a value from the ajax callback functions.
Next, disassociate the submit button from the form to prevent it from performing default submission. Test it to see it does nothing.
<form>
...
<button type="button" id="process" />
</form>
Then wire it up to make your validation request
$("#process").on("click", function() {
if (valid()) {
$(this).prop("disabled", true); // disable the button to prevent extra user clicks
// make ajax server-side validation request
}
});
Then you can make your AJAX request truly asynchronous.
$.ajax({
async: true,
...,
success: function(result) {
if (exists) {
// return true; // returning a value is futile
// make ajax AddInvoice call
}
}
});
Pseudo-code for this process
if (client-side is valid) {
server-side validation: {
on response: if (server-side is valid) {
AddInvoice: {
on response: if (successful) {
form.submit()
}
}
}
}
}
In the callback for the server-side validation you make the AddInvoice request.
In the callback for AddInvoice you call your form.submit().
In this way you nest ajax calls and wait for each response. If any fail, make the appropriate UI prompt and re-enable the button. Otherwise, you don't automatically submit the form until both ajax calls succeed and you call submit() programmatically.

Is it possible to pass a variable to jquery when it starts or every action?

I'm super new to jquery and just stractching the surface of its awesomeness so sorry if this is a really basic question but I have a button on my site that once clicked posts some data to my server and I'm wondering how to provide jquery with data I want to be posted. I have made jquery refreshless forms but they have required the user to enter something which I post but now I want to send some data that is not entered or available on the webpage.
On my site, I have a button to click on if you want to 'follow' a topic. If you follow a topic I need to send a topic_id and your user id to my server to start the process but I think putting this on my web page for jquery to capture would be confusing to users(if I can't pass variables I plan to do this approach but hide the fields). The userid/topicid is avaiable to my template engine but I'm unsure how to pass the data over to the script.
Here's a example of my script
html:
<input type='button' value='Follow' id='btnFollow'>
follow.js:
$(document).ready(function () {
$('#btnFollow').click(function() {
//$("#btnFollow").prop('value', 'Following');
if ($(this).val() == 'Follow') {
$("#btnFollow").prop('value', 'Following')
} else if ($(this).val() == 'Following') {
$("#btnFollow").prop('value', 'Follow')
$.ajax({
type: 'POST',
url: '/follow_modification',
async: true,
data: {
fe1: "test"
},
complete: function(xmlRequestObject, successString){
ymmReceiveAjaxResponse(xmlRequestObject, successString);
}
});
}
})
});
How do I get info into the function from the html? So far all my javascripts have been triggered by clicks and then take data from the page.. if I have a variable in my template called {{ user_id }} how can I pass that to the script so when a click triggers a action then it'll have the data it needs to post?
<input type="button" value="Follow" id="btnFollow" data-topic="topicid" />
$('#btnFollow').click(function() {
var topic_id = $(this).attr('data-topic');
alert(topic_id);
});
<input type='button' value='Follow {{user-id}}' id='btnFollow' data-user="{{user-id}}">
on the html side, and
$(document).ready(function () {
$('#btnFollow').click(function() {
var following = $(this).attr("data-user");
if ($(this).val() == 'Follow') {
$("#btnFollow").prop('value', 'Following')
} else if ($(this).val() == 'Following') {
$("#btnFollow").prop('value', 'Follow')
$.ajax({
type: 'POST',
url: '/follow_modification',
async: true,
data: {
fe1: following
},
complete: function(xmlRequestObject, successString){
ymmReceiveAjaxResponse(xmlRequestObject, successString);
}
});
}
})
});
on the js side.
$(document).ready((function ( data ) {
// do some thing with somevalue
})( somevalue ));
or
$(document).ready(function ( ) {
var data = $('someSelector').val()
// do some thing with somevalue
});
or
var data = 'some value';
$(document).ready(function ( ) {
// do some thing with somevalue
});

Categories

Resources