George
George

Reputation: 534

JQuery AJAX get not working correctly?

I have a partial view with this jquery script:

$("#btnGetEmpInfo").click(function () {
          var selectedItem = $('#EmployeeId').val();
          var focusItem = $('#EmployeeId')
      alert("Starting");
          $.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: "<%= Url.Action("getEmpInfo", "NewEmployee")%>?sData=" + selectedItem,
            data: "{}",
            success: function(data) {
                if (data.length > 0) {
                alert("Yeah!");
                } else {
                   alert("No data returned!");
                }
              }                   
            });
            alert("Back!");
      });  

Then in my controller I have:

 [AcceptVerbs(HttpVerbs.Get)]
    public JsonResult getEmpInfo(string sData)
    {
        return new JsonResult { Data = "test" };
    }

I can breakpoint in the controller and it is hitting, but the only "Alerts" I get are the "Starting" and "Back". Why would the data not be returned or at least hit saying no data returned?

Thanks in advance for any and all help.

Geo...

Upvotes: 0

Views: 1339

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You probably might want to improve this ajax call like this:

$.ajax({
    type: 'GET',
    url: '<%= Url.Action("getEmpInfo", "NewEmployee")%>',
    data: { sData: selectedItem },
    success: function(data) {
        // Warning: your controller action doesn't return an array
        // so don't expect a .length property here. See below
        alert(data.Data);
    }                   
});

and have your controller action accept GET requests:

[AcceptVerbs(HttpVerbs.Get)]
public JsonResult getEmpInfo(string sData)
{
    return Json(new { Data = "test" }, JsonRequestBehavior.AllowGet);
}

OK, now that we have fixed the error let me elaborate. In your code you were using an application/json content type to format your request string. Unfortunately in ASP.NET MVC 2 there is nothing out of the box that is capable of making sense of JSON requests (unless you wrote a custom json value provider factory). Then using string concatenation to append the sData parameter to the URL without ever URL encoding it meaning that your code would break at the very moment the user enters some special character such as & in the EmployeeId textbox.

Upvotes: 2

Iain
Iain

Reputation: 2309

Try adding the 'beforeSend', 'error' and 'complete' callbacks to get more info in your javascript debugger. http://api.jquery.com/jQuery.ajax/

Are you using a javascript debugger? (firebug, ie9 dev-tools, chrome dev-tools are decent ones 3 that come to mind)

Upvotes: 0

Related Questions