1

I try to call webservice using json , when i call to web service without excepted parameters , its work , but when i'm try to send parameter , ive got an error :

This is my code:

function GetSynchronousJSONResponse(url, postData) 
{

    var xmlhttp = null;
    if (window.XMLHttpRequest)
        xmlhttp = new XMLHttpRequest();
    else if (window.ActiveXObject) {
        if (new ActiveXObject("Microsoft.XMLHTTP"))
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        else
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }

    url = url + "?rnd=" + Math.random(); // to be ensure non-cached version

    xmlhttp.open("POST", url, false);
    xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    xmlhttp.send(postData);
    var responseText = xmlhttp.responseText;
    return responseText;
}


function Test() 
{
    var result = GetSynchronousJSONResponse('http://localhost:1517/Mysite/Myservice.asmx/myProc', '{"MyParam":"' + 'test' + '"}');
    result = eval('(' + result + ')');
    alert(result.d);
}

This is the error :

System.InvalidOperationException: Request format is invalid: application/json; charset=utf-8.

at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()

at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest

What is wrong ?

Thanks in advance .

5
  • the line ` url = url + "?rnd=" + Math.random();` is unnecessary, POST requests are never cached. Commented Feb 2, 2010 at 15:01
  • @Andy E: POST requests are never cached by standard, and we all know some user-agents have very low regards for standards. I won't name any (the one that usually comes to mind is fortunately not plagued by this issue). Commented Feb 2, 2010 at 15:06
  • @Andrew Moore: I must say I'm not aware of any, but then again I only use Chrome and IE. Still in cases where a POST request would be cached, the timestamp could be set in the POST data or the more appropriate if-modified-since request header could be set. Commented Feb 2, 2010 at 15:33
  • @Andy E: The culprits usually cache using a hashed version of the URL. A few mobile browsers come to my mind. Therefore the only viable solution is a GET parameter unfortunately. Commented Feb 2, 2010 at 15:51
  • @Andrew Moore: Very well, I stand corrected and will say no more on the matter :-) Commented Feb 2, 2010 at 16:00

3 Answers 3

2

U can call web service in javascript it will return JSON :)

$.ajax({
    type: "POST",
    url: '<%=ResolveUrl("~/DesktopModules/TECH_WEBRTC/Service/Users.asmx/Getprovider")%>',
    data: JSON.stringify({id:'a'}),
            contentType: "application/json; charset=utf-8",

            dataType: "json",
            processData: false,
            success: (function (providerlist) {


                var obj = jQuery.parseJSON(providerlist.d);
                providers(obj);
            }
            ),
            error: function (data)
            {

            }
 });




namespace TECH_WEBRTC.Service
 {
/// <summary>
/// Summary description for Users
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
 [System.Web.Script.Services.ScriptService]
public class Users : System.Web.Services.WebService
{



    [WebMethod]
    //[ScriptMethod(ResponseFormat = ResponseFormat.Json)]//Specify return format.
    public string Getprovider(string id)
    {

        List<Comman1> obj = new List<Comman1>();
        JavaScriptSerializer js = new JavaScriptSerializer();

        obj.Add(new Comman1{id="1"});
            obj.Add(new Comman1{id="2"});
            obj.Add(new Comman1 { id = "2" });

            //Context.Response.Write(js.Serialize(obj.ToList()));

        return js.Serialize(obj.ToList());

    }
}

}

Its working fine:)

Sign up to request clarification or add additional context in comments.

Comments

1

From what I can tell, your application cannot accept application/json as a post data format. Use application/x-www-form-urlencoded instead and set your JSON to a request parameter that you can then access using Request.Params["key"]:

xmlhttp.open("POST", url, false); 
xmlhttp.setRequestHeader(
    "Content-Type", "application/x-www-form-urlencoded; charset=utf-8"
); 
xmlhttp.send("json="+encodeURIComponent(postData)); 
var responseText = xmlhttp.responseText; 
return responseText; 

Also, as I mentioned in my comment, you can remove the following line:

url = url + "?rnd=" + Math.random(); // to be ensure non-cached version   

POST requests aren't cached and it's generally bad practice to use GET parameters with POST requests.

Comments

1

I've fixed similar problem by adding these lines into server's web.config:

<handlers>
  <add name="ScriptHandlerFactory" verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory" />
</handlers>

Check out this page: http://msdn.microsoft.com/en-us/library/bb763183.aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.