Nils Anders
Nils Anders

Reputation: 4420

My jQuery ajax function always return error

This is my jQuery ajax function

//delete individual row
jQuery('.stdtable img.delete').click(function(){
    var c = confirm('Continue delete?');
    if (c) {
        jQuery.ajax({
            url: 'market/delete/14',
            type: 'POST',
            success: function () {
                alert('success');
            },
            error: function () {
                alert("error");
            }
        });
    };
    return false;
});

And this is my controller

[HttpPost]
public ActionResult Delete(int id)
{
    Using<MarketService>().Delete(int);
    return View();
}

The code is calling my controller and everything works perfect. But the jQuery function always return says "error".

What is wrong?

Upvotes: 0

Views: 887

Answers (2)

AliRıza Adıyahşi
AliRıza Adıyahşi

Reputation: 15866

JQuery

//delete individual row
jQuery('.stdtable img.delete').click(function(){
    var c = confirm('Continue delete?');
    if (c) {
        jQuery.ajax({
            url: 'Market/Delete/14', // '@Url.Action("Delete","Market")' is better. Also you should use data attribute for ajax. like this - data : { id : 14 }
            type: 'POST',
            success: function (data) {
                alert(data.Message);
                alert(data.Success);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
    };
    return false;
});

In your ajax url, you used market/delete, in your controller name "Delete" start with capital letter. there is case sensivity between them.

Controller

[HttpPost]
public ActionResult Delete(int id)
{
   var result=new { Success="True", Message="Success"};
   Using<MarketService>().Delete(id);
   return Json(result, JsonRequestBehavior.AllowGet);
}

Upvotes: 1

Stokedout
Stokedout

Reputation: 11055

Did the code in your controller even compile? You should use the id to delete and not int which is the type

[HttpPost]
public ActionResult Delete(int id)
{
   Using<MarketService>().Delete(id);
   return View();
}

Also to test your actions without JavaScript use the tool Fiddler.

Upvotes: 1

Related Questions