1

I know there is some posts on this but they did not help me. My program run's and when I click on a button to fire a javascript nothing happens, or no response. In chrome debugger under network tab I see in red

http://wms-wsdl.company.net/mobile.asmx/ContactGet?searchField=test&office=97&person=119&user=531&organization=14

when I click on that link it shows a red circle with 500 internal server error. If I click on the response I see:

{"Message":"Invalid JSON primitive: test.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Services.RestHandler.GetRawParamsFromGetRequest(HttpContext context, JavaScriptSerializer serializer, WebServiceMethodData methodData)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}

Now I have no Idea what that means.

When I double click in that lick It shows me all my data that is supposed to be inserted into a list view (data is xml) e.g. <string xmlns="http://company.net/"> [ { "Name": "Myar", "Surname": "Tester", "Mobile": "080000000", "Email": "" ......}, etc

My javascript function is as follows:

function initContactView()
{
    alert("ContactView start test")
     var txtSearch = $("#searchTextField").val();
$.ajax({
        type: "GET",
        dataType:"json", 
        contentType: "application/json; charset=utf-8",
        crossDomain: true,
        url: "http://dsf-wsdl.company.net/mobile.asmx/ContactGet",
        data: "searchField="+txtSearch+"&office="+localStorage.getItem("office")+"&person="+localStorage.getItem("person")+"&user="+localStorage.getItem("user")+"&organization="+localStorage.getItem("organization"),
        success:successContact,
        failure: function (msg) {
            console.log(msg);
            alert(msg)
        }
    });  
    alert("ContactView End Test");
}


function successContact(data) {
    alert("Success Start Test");
    window.location = "#contactsview";
    $("#lstView_contacts").kendoMobileListView({
        dataSource: JSON.parse(data.d),
        template: $("#lstView_contact_Template").html(),
        endlessScroll: true,
        scrollThreshold: 8
    });
    alert("Success Start Test");    
}

searchTextField comes from my HTML textbox.

What I seem to find odd is that it gets the data it should, I have verified that in the xml but still gives an error. My webservice that I am using is a json webservice. It alerts both alerts but I think it goes into failure.

The response i get in debugger is:

<string xmlns="http://company.net/">[
  {
    "Name": "Myar",
    "Surname": "Tester",
    "Mobile": "080000000",
    "Email": "test@test.com"
  }]</string

How my webservice looks:

<WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
    Public Function ContactGet(ByVal searchField As String, ByVal office As String, ByVal person As String, ByVal user As String, ByVal organization As String) As String

        Dim objSearch As New ArrayList
        Dim objSearching As New Search
        Dim intResult As Integer

        Try
            'Test String
            intResult = objSearching.SearchByKeyword(searchField, person, office, organization, user, company.ETMyProperty.Search.enmSearchType.enmContact, objSearch)

            Dim objContact As New Person
            Dim dt As New DataTable("Contacts")

            Dim col_Name As New DataColumn("Name", GetType(String))
            dt.Columns.Add(col_Name)

            Dim col_Mobile As New DataColumn("Surname", GetType(String))
            dt.Columns.Add(col_Mobile)

            Dim col_Office As New DataColumn("Mobile", GetType(String))
            dt.Columns.Add(col_Office)

            Dim col_Category As New DataColumn("Email", GetType(String))
            dt.Columns.Add(col_Category)

            Dim dr As DataRow

            For i = 0 To objSearch.Count - 1
                dr = dt.NewRow()
                dr("Name") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return2
                dr("Surname") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return3
                dr("Mobile") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return6
                dr("Email") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return7
                dt.Rows.Add(dr)
            Next

            Dim serializer As New JavaScriptSerializer()
            Dim rows As New List(Of Dictionary(Of String, Object))()
            Dim row As Dictionary(Of String, Object) = Nothing

            'serialize dt row to json output
            For Each drow As DataRow In dt.Rows
                row = New Dictionary(Of String, Object)()
                For Each col As DataColumn In dt.Columns
                    row.Add(col.ColumnName, dr(col))
                Next
                rows.Add(row)
            Next

            Dim str_json = JsonConvert.SerializeObject(dt, Formatting.Indented)

            Return str_json

        Catch ex As Exception
            Return Nothing
        End Try
    End Function

I have been on this for a few days now and I cant seem to get any solution. Any help?

user3458266
  • 235
  • 1
  • 5
  • 12

2 Answers2

0

Refering to jQuery doc, you should use error: function() {...}, and not failure. The value for the key success should be a function, and not a variable. Something like success: successContact(),

For debugging in some usefull way, you NEED to know, if your ajaxcallback calls success or error. If it does not call success, it is probably because the answer has no application/json content-type header, or your json is wrong.

vekah
  • 980
  • 3
  • 13
  • 31
0

Cause you are seding a GET request, you have to remove or define the contentType as:

application/x-www-form-urlencoded; charset=UTF-8

function initContactView()
{
    alert("ContactView start test")
     var txtSearch = $("#searchTextField").val();
$.ajax({
        type: "GET",
        dataType:"json", 
        crossDomain: true,
        url: "http://dsf-wsdl.company.net/mobile.asmx/ContactGet",
        data: "searchField="+txtSearch+"&office="+localStorage.getItem("office")+"&person="+localStorage.getItem("person")+"&user="+localStorage.getItem("user")+"&organization="+localStorage.getItem("organization"),
        success:function (data) {successContact(data);},
        failure: function (msg) {
            console.log(msg);
            alert(msg)
        }
    });  
    alert("ContactView End Test");
}

Check too if the error is when the Request Begin on the ASMX or the error is on the ASMX Response.

Check this for Details Get Request: Do I need a content type for http get requests?

Also configure your webservice to return JSON. The response isn't json. So, the dataType now is not correct. To retrun ONLY json change your WebMethod.

[WebMethod]
[ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
public void HelloWorld()
{
    Context.Response.Clear();
    Context.Response.ContentType = "application/json";
    Context.Response.Write("Hello World");
    //return "Hello World";
}

Important: if you are using webmethods you don't need to parse the datatable to json, webservice will do it for you. So change this to:

<WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
    Public Function ContactGet(ByVal Parameters....) As DataTable

After all, this is an example that works with the .net serialization

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data;
using System.Collections;
using System.Linq;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 WebService : System.Web.Services.WebService {

    public WebService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
    public List<Dictionary<string, object>> HelloWorld()
    {
        DataTable TestTable = new DataTable();
        TestTable.Columns.Add("Name");
        TestTable.Columns.Add("Id");
        DataRow Row = TestTable.NewRow();
        Row["Name"] = "James";
        Row["Id"] = 0;
        TestTable.Rows.Add(Row);

        return RowsToDictionary(TestTable);
    }


    private static List<Dictionary<string, object>> RowsToDictionary(DataTable table)
    {
        List<Dictionary<string, object>> objs =
            new List<Dictionary<string, object>>();
        foreach (DataRow dr in table.Rows)
        {
            Dictionary<string, object> drow = new Dictionary<string, object>();
            for (int i = 0; i < table.Columns.Count; i++)
            {
                drow.Add(table.Columns[i].ColumnName, dr[i]);
            }
            objs.Add(drow);
        }

        return objs;
    }

}

Please, check another serializers like http://james.newtonking.com/json. Perhaps you can use better a ASHX handler than a ASMX for returning JSON.

Community
  • 1
  • 1
Jaime García Pérez
  • 953
  • 1
  • 10
  • 16
  • its on the response I see it does a request it goes through and the response shows red (error) – user3458266 Apr 10 '14 at 10:40
  • Using the code above or taking out that code work's in a way. I dont get an error any more and in network nothing is red. But I does not call my other successContact function. – user3458266 Apr 10 '14 at 10:44
  • But you will allways have a response. You should check if the ASMX fails when is trying to read the Get Parameters or fails when is building the response after your code. As i can see, you are sending a big Get String to the ASMX. I would change it to POST request (to avoid request size fails) – Jaime García Pérez Apr 10 '14 at 10:44
  • How can I see where it fails, can I use chrome debugger, if so what tab and what should i look for. Also should I change my GET to POST? – user3458266 Apr 10 '14 at 10:46
  • 1
    Put the code of the successContact. You should have at last two arguments. You should change the Get to Post if the Get String Grows. Anyway, i think is more clear to use Post than Get. If you change it you should change the ASMX code. – Jaime García Pérez Apr 10 '14 at 10:47
  • So my successContact, I am going to put it in my function after `success:`. Sorry bit new to this that's why all the questions. Ive changed it to get and my response looks right. No error. – user3458266 Apr 10 '14 at 10:51
  • still don't call other function, but like I said my response shows data in debugger. – user3458266 Apr 10 '14 at 11:04
  • 1
    i have added successContact in original post. There is an alert which is not fired. – user3458266 Apr 10 '14 at 11:09
  • SO, the console.log(msg) on the failure funcion is running?, Change the line to: success:function (data) {successContact(data);}, – Jaime García Pérez Apr 10 '14 at 11:48
  • If you only see the console log is cause the request fails (no 200 http response) its cause there is an error on the response. Check that the response gives you the Customers Details (data).Can you post the response? – Jaime García Pérez Apr 10 '14 at 12:14
  • the response posted in original post – user3458266 Apr 10 '14 at 12:30
  • The problem is that your response is XML with a json object. Please check the edit post to change your Web Method in order to return only json – Jaime García Pérez Apr 10 '14 at 14:21
  • Please check my edited original post, sorry for all the questions but you are really helping me. – user3458266 Apr 10 '14 at 14:46
  • What version of .Net are you using? its important for webservices to use 4.0 or above. With 2.0 you can have some problems. – Jaime García Pérez Apr 10 '14 at 14:58
  • Edited, i think taht your function shouldnt return a json string. You have to return the datatable, webmethod will parse it (try it). – Jaime García Pérez Apr 10 '14 at 15:02
  • The weird thing is I have a method to return tasks. That works like a bom! The two are almost identical in terms of logic but this one wont budge! – user3458266 Apr 10 '14 at 15:21
  • Return it as objSearching!! perhaps it can serialize the array. – Jaime García Pérez Apr 10 '14 at 15:22
  • I write an example that works for datatable return but you can Return the objSearching with better .net serializers as i write on the post. Hope it helps you. – Jaime García Pérez Apr 10 '14 at 15:37
  • Did you try the example? – Jaime García Pérez Apr 14 '14 at 08:13