Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ajax call returns values and my html page

I am currently performing an ajax call to my controller with the following code:

$.ajax({
    type: "POST",
    url: "@Url.Action("uploadImage", "Item")",
    data: '{ "imageData" : "' + image + '" }',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (success) {
        alert('Success ' + success.responseText);
    },
    error: function (response) {
        alert(response.responseText);
    }
});

This is the controller :

[HttpPost]
public ActionResult uploadImage(string imageData)
{
    string imageName = Guid.NewGuid().ToString();

    try
    {
        ProductManager pm = new ProductManager();
        pm.AddNewProduct(imageName);
    }catch(Exception e)
    {
        writeToLog(e);
    }
    return Json(new { success = imageName }, JsonRequestBehavior.AllowGet);
}

It gets to the controller and the AddNewProduct function runs successfully. The problem is that i want it to return the image name that is created within the controller. This works as well but with that it also return my complete html page. I alert something on success and when an error occurs but somehow it always ends up in the error with the following alert :

enter image description here

it shows the value I need but why does it return my complete HTML as well?

like image 481
Niels Peeren Avatar asked Oct 18 '22 07:10

Niels Peeren


1 Answers

  • You do not need JsonRequestBehavior.AllowGet. That must be used only for GET requests in order to protect you against a very specific attack involving JSON requests. And in your code you are using POST verb.

  • You should use follow code in order to get the success string received from server.

    success: function (response) { alert('Success ' + response.success); }

like image 178
Mihai Alexandru-Ionut Avatar answered Oct 21 '22 01:10

Mihai Alexandru-Ionut