Codehelp
Codehelp

Reputation: 4757

String mismatch in ajax call to WebApi

I have an ajax call to a WebAPI method like so:

function GetGroupDetails(Id, StudentType, GrpID) {
    var result = "";
    $.ajax({
        url: GetGrpDetails + Id + "&studenttype=" + StudentType + "&GrpId=" + GrpID, dataType: 'json',
        success: function (data) { if (data != null && data != "") { result = data; } },
        error: function (XHR, textStatus, errorThrown) { alert(textStatus + ":" + errorThrown); }
    });
    return result;
}

Here's the URL that goes to the WebAPI

/api/Students/GetGroups?Id=107&studenttype="Captain"&GrpId=88

During debugging, if the value in StudentType = "Captain" it comes in as "\"Captain\"". Now in the debugger if I replace that with "Captain" it works fine.

The actual WebApi is a simple LINQ query on an EF context object which will return a valid value if the string is as expected, null otherwise.

So, how do I get the string as required.

Regards.

Upvotes: 0

Views: 192

Answers (2)

Yasser Shaikh
Yasser Shaikh

Reputation: 47794

Remove the quotes in the url, your request url should not have it. Try this

/api/Students/GetGroups?Id=107&studenttype=Captain&GrpId=88

and the function you have written, will NEVER return any values other than "", try calling the required function in the success method of the ajax call where you will get the response.

Hope this helps.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039140

You are looking the value in VS Debugger. The actual value of the string is "Captain". I think the correct value of the string should be Captain without any double quotes. So fix your client side AJAX call.

The request should look like this:

/api/Students/GetGroups?Id=107&studenttype=Captain&GrpId=88

So basically it's your StudentType javascript variable that needs fixing. Also I would recommend you passing parameters like this to ensure proper encoding:

function GetGroupDetails(id, studentType, grpID) {
    $.ajax({
        url: GetGrpDetails,
        data: { id: id, studentType: studentType, grpId: grpID },
        success: function (data) {  
            if (data != null && data != "") { 
                // Do something with the data here but do not attempt to assign
                // it to some external variable that you will be returning
            } 
        },
        error: function (XHR, textStatus, errorThrown) { 
            alert(textStatus + ":" + errorThrown); 
        }
    });
}

Another remark about your code is returning a value from the GetGroupDetails function. You are making an AJAX call and inside the success callback you are assigning a value to the result variable which you are returning from the function. This obviously won't work because AJAX is asynchronous and by the time the success callback executes, the function would have long finished running. So never attempt to be returning any values from an AJAX call. Use it inside.

Upvotes: 1

Related Questions