1

Im trying to get a page talking to a webservice through jquery.

this is the jquery:

function Test(item) {
  $.ajax({
    type: "POST",
    url: "WebService.asmx/test",
    data: '{' +
                    'Item:"' + item + '"' +
               '}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
        var data = jQuery.parseJSON(msg);
        if (!data.error) {
            alert("YES!!");
        }
        else {
            alert("Error" + " " + data.error);
        }
    },
    error: function (msg) {
        alert('Get Details Failure: ' + msg);
    }
 });
};

This is the web service:

    using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Web.Script.Services;
using System.Web.Script.Serialization;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class WebService : System.Web.Services.WebService {

    public WebService () {}

    [WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public string Test(string Item)
    {
        JavaScriptSerializer js = new JavaScriptSerializer();
        string strJSON = js.Serialize(Item);
        return strJSON;
    }
    }

but i get his 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()

why???

2
  • Not directly related to your question, you shouldn't manually use JavaScriptSerializer in a ScriptService. ASP.NET is already doing that automatically: encosia.com/… Commented Jan 16, 2012 at 17:35
  • "; charset=utf-8" is not needed in your content type Commented Jul 16, 2012 at 0:51

5 Answers 5

1
 data: '{' +
                    'Item:"' + item + '"' +
               '}',

needs to be:

data: JSON.stringify({Item: item}),

that will produce:

'{"Item": "item's value"}'

That is valid json. You were missing the " around Item


In addition:

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string Test(string Item)
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    string strJSON = js.Serialize(Item);
    return strJSON;
}

should be:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Test(string Item)
{
    return Item;
}

You don't need to serialize that string.

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

Comments

0

Your JSON doesn't look valid to me. Values and keys should be surrounded by quotations, like this:

'{ "Item" : "' + item + '" }'

EDIT; Maybe something to do with your web.config. Check out this persons solution.

1 Comment

sorry still hasnt made a difference
0

Seems to be a malformed JSON string.

Alse you might want to have a look at this free library for parsing / writing JSON in .NET !

NewtonSoft's JSON Library for .NET

It's quite simple to use, offers a lot of methods and you won't have to rely on Javascript parser.

Comments

0

As the other answers have stated, you have some JSON issues.

First off, you're using a JSONSerializer in your web service for your return value - but if you're just using a string, there's no reason to use the JSONSerializer. I'm assuming you're doing more than that, so I have an example at the bottom that may simulate what you're trying to do.

Second, you're trying to parse your return value in your JavaScript even though the JSONSerializer wraps your JSON object inside another object ("d") when it serializes it. So what you want to deserialize in your JavaScript is msg.d, not just msg. Once you do that, you'll get the underlying object literal.

I enhanced the service logic a bit just to get some different results based upon what is sent in. But I think if you handle your JSON appropriately, knowing the JSONSerializer sticks your object inside another, you'll be good to go.

EXAMPLE

default.htm

<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript" src='http://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type="text/javascript">
    $(document).ready(function () {
        Test('stuff');
        Test('balh');
    });

    function Test(item) {
        var item = { Item: item };
        $.ajax({
            type: "POST",
            url: "WebService.asmx/Test",
            data: JSON.stringify(item),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                var data = JSON.parse(msg.d);
                alert(data);
                if (!data.error) {
                    alert("YES!!");
                }
                else {
                    alert("Error" + " " + data.error);
                }
            },
            error: function (msg) {
                alert('Get Details Failure: ' + msg);
            }
        });
    };
</script>

WebService.asmx.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Web.Script.Services;
using System.Web.Script.Serialization;

namespace WebApplication1
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ScriptService]
    public class WebService : System.Web.Services.WebService
    {

        public WebService() { }

        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string Test(string Item)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();

            string strJSON;
            if (Item=="stuff")
            {
                var returnValue = new { Item = "stuff", success = true };
                strJSON = js.Serialize(returnValue);
            }
            else
            {
                var returnValue = new { Item = "boo", error = true };
                strJSON = js.Serialize(returnValue);
            }

            return strJSON;
        }
    }
}

Comments

0

Let me describe what I got from your questions.

  1. You want to have webservice method something like public string HelloWorld(string name) where name is your input from the asp page and some string say Hello Gud Morning Mr XYZ is the returned to the asp page.

  2. You want to use JSON format for data interchange between the view and the webservice.

  3. You want to use the JQUERY AJAX for achieving the requirements,

Then I am here with the answer.

Click her for details

WebService

       <%@ WebService Language="C#" %>
        using System;
        using System.Data;
        using System.Data.SqlClient;
        using System.Configuration;
        using System.Web;
        using System.Web.Services;
        using System.Web.Services.Protocols;
        using System.Collections;
        using System.Web.Security;
        using System.Web.UI;
        using System.Web.UI.WebControls;
        using System.Web.UI.WebControls.WebParts;
        using System.Web.UI.HtmlControls;

        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

        // To allow this Web Service to be called from script, using ASP.NET AJAX or JQuery.

        [System.Web.Script.Services.ScriptService]
        public class WebService  : System.Web.Services.WebService {

        [WebMethod]
            public string HelloWorld(string name)
            {
                Utility ut = new Utility();  // some class where you will have your database connection
                ArrayList suggestedProblemName = ut.getItems(name);  // some method of the class
            return ""+suggestedProblemName[0];
            }
        }

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.