Reputation: 966
I have a wcf service runing which contains a method that returns a string. I am able to run the service in the browser successfully. Moreover I can even pass the required parameters and can see the result in the browser.
But when i am trying to invoke the same method from javascript client the parameter value does not get passed to the method and hence it returns nothing.
Here is what my service retuns when run from the browser
Here is my interface Implementation:
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped)]
string JSONData(string id);
Here is my service Method implementation code:
public string JSONData(string id)
{
if (id == null || id == "")
{
return "Id is null";
}
else
{
return "You requested product " + id;
}
}
As shown above service works fine fine a parameter is passed from the url. However when I make the call using jquery's function parameter doesnot get passed Here is my javascript client's code:
<script type="text/javascript">
// A $( document ).ready() block.
$(document).ready(function () {
// alert("pass");
var valu = "123";
$("#btnclick").click(function () {
debugger;
$.ajax({
cache: false,
type: "GET",
async: false,
url: "http://localhost:35798/RestServiceImpl.svc/JSONData",
data: JSON.stringify(valu),
contentType: "application/json",
dataType: "json",
success: function (result) {
var ans = JSON.stringify(result);
alert("success");
alert(ans);
},
error: function (xhr) {
alert("error");
alert(xhr.responseText);
}
});
});
});
</script>
I want to be able to pass the parameter from the jquery code. Any suggestions to get this working would be really appreciated.
Upvotes: 1
Views: 5198
Reputation: 22553
valu needs to be a key value pair:
var valu = {id:"123"};
Or a string:
var value = 'id="123"';
In order to currently form the proper request.
Pass it as a plain JavaScript object in the first case, do not stringify it. If you do jquery will append it as a string to the request.
Use the network debugging tools in your browser to work through these sorts of issues.
This will correctly serialise your query string to /JSONData?id=123
as opposed to your solution which produces /JSONData/"123"
Your code with edits...
<script type="text/javascript">
// A $( document ).ready() block.
$(document).ready(function () {
// alert("pass");
var valu = {id: "123"};
$("#btnclick").click(function () {
debugger;
$.ajax({
cache: false,
type: "GET",
async: false,
url: "http://localhost:35798/RestServiceImpl.svc/JSONData",
data: valu,
contentType: "application/json",
dataType: "json",
success: function (result) {
var ans = JSON.stringify(result);
alert("success");
alert(ans);
},
error: function (xhr) {
alert("error");
alert(xhr.responseText);
}
});
});
});
</script>
Upvotes: 1