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?
3
Answers
Always write your jquery functions like this, as per documentation. (The always is optional)
So in your case:
And maybe change alerts to console log or similar.
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.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 fordone
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:And the js function: