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');
Related
I'm trying to figure out how to be able to export an iCal file from my calendar. I can't get it to work, it does not start to "download" the file.
Right now I just try to get one meeting, but later on I will make a for loop to get all the meetings in the database to the iCal file, but I just want to check if it works, but it does not.
This below is my method in the controller and later the jQuery to call the method.
[HttpPost]
public ActionResult AddToICalendar()
{
var ctx = new OruBloggenDbContext();
var meetings = ctx.Meetings.FirstOrDefault(u => u.MeetingID == 1);
var icalStringbuilder = new StringBuilder();
icalStringbuilder.AppendLine("BEGIN:VCALENDAR");
icalStringbuilder.AppendLine("PRODID:-//MyTestProject//EN");
icalStringbuilder.AppendLine("VERSION:2.0");
icalStringbuilder.AppendLine("BEGIN:VEVENT");
icalStringbuilder.AppendLine("SUMMARY;LANGUAGE=en-us:" + meetings.MeetingTitle);
icalStringbuilder.AppendLine("CLASS:PUBLIC");
icalStringbuilder.AppendLine(string.Format("CREATED:{0:yyyyMMddTHHmmssZ}", DateTime.UtcNow));
icalStringbuilder.AppendLine("DESCRIPTION:" + meetings.MeetingDesc);
icalStringbuilder.AppendLine(string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", meetings.MeetingStartDate));
icalStringbuilder.AppendLine(string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", meetings.MeetingEndDate));
icalStringbuilder.AppendLine("SEQUENCE:0");
icalStringbuilder.AppendLine("UID:" + Guid.NewGuid());
icalStringbuilder.AppendLine("END:VEVENT");
icalStringbuilder.AppendLine("END:VCALENDAR");
var bytes = Encoding.UTF8.GetBytes(icalStringbuilder.ToString());
return this.File(bytes, "text/calendar", "ical.ics");
}
Javascript:
<script>
$(function () {
$(document)
.on("click", "#icalBtn", function () {
exportiCal();
});
function exportiCal() {
$.ajax({
url: '/MeetingCalendar/AddToICalendar',
type: "POST",
//data: { downloadFileName = "thisEvent.ics" },
success: function (data) {
alert("hejejje");
}
});
}
});
</script>
The reason nothing downloads is because you can't download files via AJAX. Instead of being delivered to a file on your computer's disk, the downloaded content is going into the data variable in your "success" function.
To solve it, instead of using AJAX, make your action method accept GET requests and just user a regular hyperlink to link the user to it:
[HttpGet]
public ActionResult AddToICalendar()
{
//..etc
and
Download to iCalendar
You can remove all your jQuery code.
N.B. Logging that data value to the console (instead of just alerting meaningless junk) - or using your browser's network tools to see what is going on - would have let you see that, and you might have seen the problem sooner...maybe you need to do a bit more debugging in future.
I'm trying to call a confirm, then an alert function from an MVC action link and I'm stuck. The code is as follows:
My view has the following actionlink:
#Html.ActionLink("JQuery Testing", "BuildProject", Model, new { onclick = " return ConfirmProjectSubmit()" })
which calls the controller to save a project to the database. I'm trying to throw a confirm statement onClick. Once that action is performed, the following action is called:
return RedirectToAction("ProjectDetails", "Project", new RouteValueDictionary(new { id = currentProject.Id, msg = message }));
to alert the user that the project was actually created.
and then at the bottom of my view:
#section scripts {
<script type="text/javascript">
function ConfirmWorkflowSubmit() {
$.confirm({
title: 'Confirm!',
content: 'Simple confirm!',
buttons: {
confirm: function () {
},
cancel: function () {
}
}
});
return false;
};
</script>
#if (ViewBag.message != null)
{
<script type="text/javascript">
$(document).ready(function () {
$.alert({
title: 'Workflow successfully created',
content: '#ViewBag.message',
type: 'green',
});
});
</script>
}
}
both of the actions are firing, but incorrectly. I'm newer to MVC and moreso to Jquery. Basically I need to figure out how to not have it submit if the user doesn't confirm, and then make sure the message only pops on the way back. I think I just need help ordering what I have properly.
Thanks in advance.
EDIT. Okay, so I see part of the problem. It's not the $confirm function that's actually submitting the form, it's the button action clicked once the dialog is open. I'm really stuck here, and this has to be easier than I'm making it. Help!
I'm not saying you can't do it the way you have, but this is normally how I set up my bindings:
$(document).ready(function ()
{
// add the e here -- it is the event which initiated the binding
$(".buildButton").on("click", function (e)
{
if (ConfirmProjectSubmit())
{
alert('confirm');
}
else
{
// e.preventDefault() cancels the click action
e.preventDefault();
alert('cancel');
}
});
});
function ConfirmProjectSubmit()
{
// some confirm logic
// return true for confirmed, false for cancelled
return false;
}
Remove the onclick in your action. There is no need to have a jQuery binding and an onClick.
This is sort of an outline, you can add your logic in various places to finish it out.
I have ajax function as:
function LoadTeacherObservationData(_CategoryID, _SearchText) {
alert("In here");
alert(_CategoryID);
alert(_SearchText);
flag = 1;
$.ajax({
url: "PP/getTeacherObservationData",
data: {
'CategoryID': _CategoryID,
'SearchText': _SearchText
},
dataType: "json",
type: 'POST',
cache:false,
success: function (data) {
OnlebelChange(_CategoryID);
$('#hdnCategoryID').val(_CategoryID);
$("#lvTeacherData").kendoListView({
dataSource: data,
dataBound: function(e) {
if(this.dataSource.data().length == 0){
//custom logic
$("#lvTeacherData").append("<h4> No record found.</h4>");
}},
template: kendo.template($("#lvTeacherData_Template").html())
});
},
error: function () {
alert("error in click");
}
});
}
I have made sure that function is getting called with correct parameters as i have checked it through alert box.
My problem is its not getting rendered to:
PP/getTeacherObservationData as i have mentioned in URL.
PP is my controller and getTeacherObservationData is my function.
I have written that function as follows:
public JsonResult getTeacherObservationData(string CategoryID, string SearchText)
{
try
{
if (CategoryID == "1")
return Json(new TeacherObservation().ScheduledObserVations(SearchText));
if (CategoryID == "2")
return Json(new TeacherObservation().InProcessObservations(SearchText));
if (CategoryID == "3")
return Json(new TeacherObservation().CompletedObservations(SearchText));
return Json(new List<TeacherObservation>());
}
catch (Exception ex)
{
throw ex;
}
}
Instead of calling this function ajax function code goes in error block and gives me alert as: error in click
What can be the problem??
Please help me.
I want to make function call through ajax.
Using MVC4.
Expanding on my comment: the URL PP/getTeacherObservationData is relative so if you are currently not in the root of the site, then this won't work.
Using a forward slash prefix /PP/getTeacherObservationData will work if your site is in the root of the domain.
You could also use one of the solutions in this answer. Such as ResolveUrl("~/") to dynamically get the site's root, which is better because it's more portable. For example if you move your site out of the domain's root and into a directory, this will continue to work unlike hard coding the root.
I don't know what PHP Framework you are using, but normally you can't just return a value to an AJAX call, you have to ouput it somehow to send it back to the caller. Try to use echo or print instead of return.
To prevent further rendering (if any), you should somehow end the script after it has echoed your specified JSON.
You should also check for the output that is rendered in firebug or similar consoles to see if you get a plain JSON (which you obvoiously expect) or some HTML wrapped content which is rendered by your php framework and connot be parsed.
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()
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 }).