Unwanted page refresh after AJAX request that runs SQL - c#

On click of a button, I want to delete something from my database.
The following is my click handler.
$('.deleteLesson').click(function () {
$.get('/Assignment/Modules/DeleteLesson.cshtml?LessonID=' + lessonID,function(data){
});
});
Inside DeleteLesson.cshtml, I have the following
var db = Database.Open("database");
db.Query("DELETE FROM Lessons WHERE LessonID=#0", Request.QueryString["LessonID"]);
When the $.get runs, the SQL is performed on my database, but it forces a refresh on my original page. I can't figure out why. Through troubleshooting I have discovered it is purely the db.Query line that causes the refresh, and nothing else.
To be clear: I can comment out the db.Query line and it works exactly as I want it to (except it doesn't delete the item)

I don't know whether to laugh or cry... it turns out my live.js was forcing the refreshes as it saw changes and wanted to update the page for me. (As intended, I just never expected it to do it in these circumstances).
Thanks for the help everyone...

A bit long for a comment - but the fact that it works when not running the query is interesting. What happens if you try the following from the documentation page:
Request the page and ignore the results - (simplest call):
$('.deleteLesson').click(function () {
$.get('/Assignment/Modules/DeleteLesson.cshtml?LessonID=' + lessonID);
});
Alert on each of the possible outcomes - see if the handlers invoked make sense or get called at all:
var url = '/Assignment/Modules/DeleteLesson.cshtml?LessonID=' + lessonID;
var jqxhr = $.get(url, function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
What about doing this as a post:
$.ajax({
type: "POST",
url: "/Assignment/Modules/DeleteLesson.cshtml",
data: { LessonID: lessonID }
})
.done(function() {
alert( "Record Deleted" );
});
Finally, have you tried invoking with $.ajax instead of the $.get shorthand? This gives you access to additional options.

Try with
$('.deleteLesson').click(function (e) {
e.preventDefault();
$.get('/Assignment/Modules/DeleteLesson.cshtml?LessonID=' + lessonID,function(data){
//code here
});
});

Try this:
$('.deleteLesson').click(function (el, event) {
event.preventDefault();
$.get('/Assignment/Modules/DeleteLesson.cshtml?LessonID=' + lessonID,function(data){
});
});
also check that lessonID is being passed correctly to the QueryString collection. The SQL Query may be failing because of this.

Create an action in your controller and don't use call to a cshtml page.
public class LessonControler{
[AllowGet]
public JsonResult DeleteLesson(long LessonID){
//DoTheDeletion magic here
return Json(new {Done="OK", Error=""}, JsonRequestBehavior.AllowGet);
}
}
And change the javascript to match the new action call
$('.deleteLesson').click(function () {
$.get('/Lesson/DeleteLesson?LessonID=' + lessonID,function(data){
});
});
Or even better transform this to Post jQuery.post()

Related

Why does my function stop working without an alert?

So I've got this function right here in my view:
function izbrisi() {
var b = document.getElementById('proizvod').value;
{
$.ajax({
url: '#Url.Action("IzbrisiProizvod", "Proizvod")',
data: { id: b }
}).done(function () {
alert('Izbrisan');
});
alert('Izbrisan'); #* bez ovoga se ne brise proizvod *#
}
}
The controller it's passed to:
public ActionResult izbrisiProizvod(int Id)
{
RadniProizvod.IzbrisiProizvod(Id);
return View();
}
And finally the "IzbrisiProizvod" method:
public void IzbrisiProizvod(int IdProizvoda)
{
Proizvod izbrisaniProizvod = azilEntities.Proizvods.FirstOrDefault(x => x.idProizvoda == IdProizvoda);
azilEntities.Proizvods.Remove(izbrisaniProizvod);
azilEntities.SaveChanges();
}
For whatever reason, if I don't add the final alert (the one where there's a comment), the code just will not work. Nothing gets deleted, nothing gets reported to the console. As soon as I add in the final alert, it will magically start working.
Can someone explain this magic to me?
Always write your jquery functions like this, as per documentation. (The always is optional)
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function(jqXHR, textStatus, errorThrown) {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
So in your case:
function izbrisi() {
var b = document.getElementById('proizvod').value;
{
$.ajax({
url: '#Url.Action("IzbrisiProizvod", "Proizvod")',
data: { id: b }
}).done(function () {
alert('Izbrisan');
}).fail(function() {
alert( "error" );
}).always(function() {
alert( "complete" );
});
}
}
And maybe change alerts to console log or similar.
Try Network tool within your browser dev tools. For example for Firefox Dev Tools. When you click your element (let's say button) you should see new http request in the list of all request within Network tool. If you don't then your ajax call didn't happen at all or it was happen on previous page because you've experienced page reloading. Check if Proizvod actually deleted. If it is then your js function works but you don't see response. If there is s new http request within Network tool, inspect it a little bit to see what is happen (just click on it and in the right you will see details).
Also, you can open console and instead click the html element type in your console: izbrisi(). Function should execute and if it works you will see a new http request in Network tool and your alert for done will popup. If this is the case then your html element has default behavior on click event. So you should prevent it in order to prevent page reloading. Let say that you use a button for click on it. The button html should look like:
<button onclick="izbrisi(e)">Izbrisi</button>
And the js function:
function izbrisi(e) {
e.preventDefault();
// ... your code goes here
}
For whatever reason, if I don't add the final alert (the one where there's a comment), the code just will not work. Nothing gets deleted, nothing gets reported to the console. As soon as I add in the final alert, it will magically start working.
Your ajax only contains the .done() promise callback. This will only execute if the ajax request receives a 200 success code. You can add in the .fail() promise to with a unique alert to see what is happening.
In your code, the final alert is fired no matter what.
Try this to help see what is going on. Use this fiddle and open your console also. Note the different alert messages in the .done() and .fail() promises.
//var b = document.getElementById('proizvod')?.value;
$.ajax({
url: '#Url.Action("IzbrisiProizvod", "Proizvod")',
data: {
id: 'someData'
}
}).done(function() {
alert('success');
}).fail(function() {
alert('error');
});
console.log('i fire no matter what');

Jquery .post method is sending a null value. How to pass actual value to controller?

I have a controller that applies to an edit view in asp.net MVC. I have an actionlink that sends the row Id to the controller which then brings back the correct row to see in the associated view.
I then have a partial view below that. That also requires a parameter in order to bring associated data from another table.
I have a Jquery .post call that runs after the page is loaded. I can alert out and show the exact value I want to send to the controller.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").serialize();
alert(Uc);
$.post(url, {Id: Uc}, function (data) {
alert("what is Uc now? " + uc); //just for testing
});
})
I have also used it this way.
$(document).ready(function () {
var url = "/Home/MmsAndNotes";
var Uc = $("#Id").val();
alert(Uc);
$.post(url, Uc, function (data) {
});
})
the alerts come up and show the value I want. However, when the .post call runs, it sends a null value. Here is my controller.
public ActionResult MmsAndNotes(string Id)
{
//Declare LogisticsVM for individual policy info
LogisticsMMS_NotesVM model;
if(uc == null)
{
return Content("uc is empty.");
}
int val = Convert.ToInt32(uc);
using (Db db = new Db())
{
LogisticsMMS_NotesDTO dto = db.LogisticsMMS.Find(val);
//confirm policy exists
if (dto == null)
{
return Content("This policy cannot be found." + val);
}
model = new LogisticsMMS_NotesVM(dto);
}
return PartialView(model);
}
It always returns as uc is empty. I repeat, when the alerts come up. I get the correct value to send to the controller. But once it sends, something happens and it converts to null. HELPPPPP.. please .. I'm losing my mind over this one.
I don't know why, but changing my $.post() call to an $.ajax({}) call solved the issue. As you can see above, I had the $.post call. Using this instead,
$.ajax({
type: "POST",
url: "/Home/MmsAndNotes",
dataType: 'text',
data: { Id: Uc }
});
Solved it. I thought Jquery's shortened calls worked the same way. They certainly might, but doing it this way was the only way it worked for me.
P.S. Thanks Tyler (above) for your comments.
this solution should be work :
$(document).ready(function () {
$.ajax({
url: '/Home/MmsAndNotes',
type: 'GET',
dataType: "html",
data: { uc : $("#Id").val() },
success: function (result) {
code here
}
});
})
You need to verify if $("#Id").val() is not empty

MVC AJAX POST request redirects to originating page as GET

Hopefully someone can point me in the right direction with this, have been scratching my head all day over it and am developing a bald spot. I have spent a lot of time on SO, but none of the questions I found seemed to pertain to my exact problem.
Briefly, I have a dropdown list and want to give users the ability to add entries to the list in realtime. I intended on using AJAX to send form info to a controller whereupon it would be entered into the table, re-queried and then delivered back to the page as a JSON array whereupon I would parse it and replace the data in the Select dropdown.
However, what happens is that the POST request occurs, and at some point during the data processing the page refreshes and the data is appended to the URL as a GET request.
The AJAX request:
$(document).on("click", "#save-new-range", function (e) {
e.preventDefault;
var loc = window.location.href;
var url = stripURL('Data/addRange', loc); // Format the target URL correctly
$.post(url, $("#add-range-form").serialize())
.done(function (response) {
debugger;
alert(response);
});
});
StripURL function (just in case!)
function stripURL(url, loc) {
var res = "";
if (loc.search("Surveys/New") !== -1) {
res = loc.replace("Surveys/New", "");
} else if (loc.search("Surveys/Amend") !== -1) {
res = loc.replace("Surveys/Amend", "");
} else if (loc.search("Surveys/") !== -1) {
res = loc.replace("Surveys/Amend", "");
}
if (res.search("#") !== -1) {
res = res.replace("#", "");
}
url = res + url;
return url;
}
The Controller(without the queries and inserts):
[HttpPost]
public JsonResult addRange(FormCollection fc)
{
{
... Do data processing and query data into a dictionary called res ...
}
return Json(res);
}
Debugging, My controller actions are processed and res is populated with the correct data, but the .done() function is never entered due to the redirect.
Am happy to post the full controller, but have left it out for the sake of brevity. Let me know if you want to see it.
You are using e.preventDefault without calling it as a function. This will not run. That is why return false; works as in the accepted answer. Using e.preventDefault() as a function call would not require the return false;.
$(document).on("click", "#save-new-range", function (e) {
// called as a function
e.preventDefault();
var loc = window.location.href;
var url = stripURL('Data/addRange', loc); // Format the target URL correctly
$.post(url, $("#add-range-form").serialize())
.done(function (response) {
debugger;
alert(response);
});
});
You can test this in the console of SO like this:
$('a').click(function(e){
e.preventDefault();
});
This will stop any a tag from it's default behavior. If you leave out the function call it does nothing.
$(document).on("click", "#save-new-range", function (e) {
e.preventDefault;
var loc = window.location.href;
var url = stripURL('Data/addRange', loc); // Format the target URL correctly
$.post(url, $("#add-range-form").serialize())
.done(function (response) {
debugger;
alert(response);
});
return false;
});
See if this does the trick.

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

I want to redirect from one page to another page in ASP.NET MVC 3.0 using JavaScript/jQuery/Ajax. On button click event I have written JavaScript code like below.
function foo(id)
{
$.post('/Branch/Details/' + id);
}
My controller code is like this:
public ViewResult Details(Guid id)
{
Branch branch = db.Branches.Single(b => b.Id == id);
return View(branch);
}
When I click on a button it is calling the Details action inside BranchController, but it doesn't return to the Details view.
I didn't get any error or exception. It's showing status 200 OK in Firebug. What is wrong in my code and how can I redirect to the Details view page?
You are not subscribing to any success callback in your $.post AJAX call. Meaning that the request is executed, but you do nothing with the results. If you want to do something useful with the results, try:
$.post('/Branch/Details/' + id, function(result) {
// Do something with the result like for example inject it into
// some placeholder and update the DOM.
// This obviously assumes that your controller action returns
// a partial view otherwise you will break your markup
});
On the other hand if you want to redirect, you absolutely do not need AJAX. You use AJAX only when you want to stay on the same page and update only a portion of it.
So if you only wanted to redirect the browser:
function foo(id) {
window.location.href = '/Branch/Details/' + id;
}
As a side note:
You should never be hardcoding urls like this. You should always be using url helpers when dealing with urls in an ASP.NET MVC application. So:
function foo(id) {
var url = '#Url.Action("Details", "Branch", new { id = "__id__" })';
window.location.href = url.replace('__id__', id);
}
This could be done by using a hidden variable in the view and then using that variable to post from the JavaScript code.
Here is my code in the view
#Html.Hidden("RedirectTo", Url.Action("ActionName", "ControllerName"));
Now you can use this in the JavaScript file as:
var url = $("#RedirectTo").val();
location.href = url;
It worked like a charm fro me. I hope it helps you too.
You can use:
window.location.href = '/Branch/Details/' + id;
But your Ajax code is incomplete without success or error functions.
// in the HTML code I used some razor
#Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));
// now down in the script I do this
<script type="text/javascript">
var url = $("#RedirectTo").val();
$(document).ready(function () {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Controller/Action',
success: function (result) {
if (result.UserFriendlyErrMsg === 'Some Message') {
// display a prompt
alert("Message: " + result.UserFriendlyErrMsg);
// redirect us to the new page
location.href = url;
}
$('#friendlyMsg').html(result.UserFriendlyErrMsg);
}
});
</script>
<script type="text/javascript">
function lnkLogout_Confirm()
{
var bResponse = confirm('Are you sure you want to exit?');
if (bResponse === true) {
////console.log("lnkLogout_Confirm clciked.");
var url = '#Url.Action("Login", "Login")';
window.location.href = url;
}
return bResponse;
}
</script>
check the code below this will be helpful for you:
<script type="text/javascript">
window.opener.location.href = '#Url.Action("Action", "EventstController")', window.close();
</script>

update field or redirect page using jquery and asp.net mvc

Im new to jquery and stuck with what i want to achieve.
Heres what I want to do using jquery and asp.net mvc.
click a submit button
this calls an action method called LogOn in the controller Account
if the call allows users to log in succesfully redirect to a url (sepecified by LogOn)
if it fails replace a div(with id="error") with "sorry error occured"
so far I tried this:
$("#submit")
.button()
.click(function () {
$.ajax({
type: "POST",
url: "Account/LogOn",
dataType: "json",
success: function (data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#error2").replaceWith(data.error);
}
}
});
});
how do I construct the relevant bits in the action method? to make this work?
and is the jquery code ok? i suspect prob not.
Thanks
If you want to redirect asp.net page at same directory , you can by Jquery/Java script by this :
$("#ctl00_iframecontent_BtnCancle").click(function () {
window.location = "IncSLAList.aspx?bi=37";
});
and
To redirect to Another page of project , can use :
window.location.href = "http://ImageUpload/Welcome.aspx?
Your jQuery is almost correct:
Don't call .button() (unless you're using jQuery UI and want to do that)
Add return false; at the end of the click handler to prevent the browser from submitting normally.
In the action, you would either return Json(new { redirect = str }) or return Json(new { error = str }).

Categories