Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Error on CRM 2011 Form using JSONP cross-domain JavaScript data retrieval from web service

Posted on by 1,579

SECTION 1

 

I have cross domain JSONP compliant web service which is capable of being accessed cross-domain via JavaScript.

 

The web service is sitting out at http://aloyegeneraltest1.aloye.com/ for the purposes of being universally accessible for 24/7 troubleshooting and debugging.

 

The specific Web Method we are dealing with here is GetBusinessInfoWithParamJSON – the third one down from the top if you go out to the web service at the above hyperlink.

 

The specific web service code that is relevant to this question is shown below:

SECTION 2

 

[WebMethod]
    [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
    public void GetBusinessInfoWithParamJSON(string symbol)
//When the function is called via JavaScript from a cross-domain setting, it must pass MSFT as the symbol to get the expected data back
    { 
       //START**** Creation of Bogus Data To Allow for Troubleshooting
        showBusinessInfo[] result = new showBusinessInfo[] 
        { 
            new showBusinessInfo()
            {
                symbol="MSFT",
                name="Microsoft Corporation",
                price= 1377.73
            },
        
        };
//END**** Creation of Bogus Data To Allow for Troubleshooting
            
if (symbol == "MSFT" || symbol == "msft")
        {

            StringBuilder sb = new StringBuilder();
            JavaScriptSerializer js = new JavaScriptSerializer();
            sb.Append(symbol + "(");
            sb.Append(js.Serialize(symbol));
            sb.Append(");");
            Context.Response.Clear();
            Context.Response.ContentType = "application/json";
            Context.Response.Write(js.Serialize(result[0]));

        }
        else
        {
            StringBuilder sb = new StringBuilder();
            JavaScriptSerializer js = new JavaScriptSerializer();
            sb.Append(symbol + "(");
            sb.Append(js.Serialize(symbol));
            sb.Append(");");
            Context.Response.Clear();
            Context.Response.ContentType = "application/json";
            Context.Response.Write(js.Serialize("symbol: Invalid Entry"));
                    }
     }


SECTION 3

When I access the above shown Web Method directly from the Web Service’s test page (as shown below), I get the expected result, via JSON file.

 


 

SECTION 4

 

Fiddler shows the following, which is expected. So far so good.

 

 

SECTION 5

 

My problem occurs when I try and do this from JavaScript cross-domain.

 

The specifics of my problem are provided in the next area of the document.

SECTION 6

 

I have JavaScript client Application sitting out at http://clientsidegeneraltest1.aloye.com/ for the purposes of being universally accessible for 24/7 troubleshooting and debugging.

 

The specific section we want to focus on is the Test – Parameters JavaScript button as circled in orange shown via the image below.

 

SECTION 7

 

The current JavaScript code that sits on that button is:

function JScriptGetBusinessInfoWithParamJScript() {
            //debugger;
            $.ajax({
                crossDomain: true,
                contentType: "application/json; charset=utf-8",
                url: "aloyegeneraltest1.aloye.com/.../GetBusinessInfoWithParamJSON",
                data: ({ symbol : 'MSFT'}),
                dataType: "jsonp",
                type: "POST",
                success: function (data) {
                    if (true) { alert("Success True: " + data); }
                    alert(data);
                },
                error: function (xhr, status, error) {
                    if (true) { alert("Failure-True: " + error.statusText); }
                    //alert(error.statusText)
                }
            });

        }


SECTION 8

 

When I click the button while in debug mode within visual studio and with fiddler up, I can see that the request passes through and the results come back in JSON format as shown below.

SECTION 9

 

However, in spite of this, there is still some kind of error when the data gets back to the JavaScript as shown below. It doesn’t like the colon character, even though the colon character is the correct format for serialized data returned via JSONP.

SECTION 10

 

If I click the continue button while at that script error prompt from inside visual studio, the result is that the Ajax code fires “error” and not success, causing the error alert to pop up shown below.

This is the problem I need help solving. Clearly it is “skipping passed success” meaning its failing, and going directly to error because we get the “Failure-True” alert as shown above.

function JScriptGetBusinessInfoWithParamJScript() {
            //debugger;
            $.ajax({
                crossDomain: true,
                contentType: "application/json; charset=utf-8",
                url: "aloyegeneraltest1.aloye.com/.../GetBusinessInfoWithParamJSON",
                data: ({ symbol : 'MSFT'}),
                dataType: "jsonp",
                type: "POST",
                success: function (data) {
                    if (true) { alert("Success True: " + data); }
                    alert(data);
                },
//******THE CODE ENDS UP EXECUTING THIS ALERT BOX ******************
                error: function (xhr, status, error) {
                    if (true) { alert("Failure-True: " + error.statusText); }
//******THE CODE ENDS UP EXECUTING THIS ALERT BOX END ******************

                    //alert(error.statusText)
                }
            });

        }

Ultimately, I need to fix this error issue with the ajax code via JavaScript so that success occurs, instead of error.

 

And on success, I need to grab the value of symbol, which is MSFT and put that in a variable which I can then pop up via an alert.

 

I also need to grab the value of name, which is Microsoft Corporation and put that in a variable which I can then pop up via an alert.

 

Finally, I need to grab the value of price, which is 1377.73 and put that in a variable

 

The expected result it to get a JSON file back, just like the JSON file that comes back (shown below) in SECTION 3 above.

 



SECTION 11

 

So, getting back to the objective – the goal is twofold:

 

  1. to determine what must be done to prevent the script error shown below from occurring and implement that to correct the JavaScript Ajax code so that the code ends in Success instead of Error

     

  2. to grab the value of symbol, name, and price out of the results and place them in variables so that I can then set them in alert messages and ultimately set them in a text field on a Dynamics CRM 2011 form.

 

For the purposes of this particular submission, I am just concerned with fixing the code so that success occurs instead of failure. I can handle item # 2 separately on its own.

 

I am so close but not quite there. ANY help would be greatly appreciated.

 

*This post is locked for comments

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Error on CRM 2011 Form using JSONP cross-domain JavaScript data retrieval from web service

    Good job Jim. I liked your post and your determination to get it done. I guess you were able to show these values on your CRM form? Do you have CRM online or on prem? Thank you!

  • Verified answer
    ACECORP Profile Picture
    ACECORP 1,579 on at
    RE: Error on CRM 2011 Form using JSONP cross-domain JavaScript data retrieval from web service

    I solved my own problem  by doing the two things listed below:

    First, I changed the JavaScript code in my Client Side App to:

    function AloyeCallBackFunction(json) { console.log(json); }
    
         
    function JScriptGetBusinessInfoWithParamJScript() {
                //debugger;
                $.ajax({
                    crossDomain: true,
                    contentType: "application/json; charset=utf-8",
                    url: "aloyegeneraltest1.aloye.com/.../GetBusinessInfoWithParamJSON",
                    //data: "{'symbol':'" + JSON.stringify("MSFT") + "'}",
                    data: ({symbol :'MSFT'}),
                    dataType: "JSONP",
                    jsonpCallback: "AloyeCallBackFunction",
                    type: "POST",
                    success: function (data) {
                        if (true) { alert("Success True: " + data); }
                        //alert(data);
                    },
                    error: function (xhr, status, error) {
                        if (true) { alert("Failure-True: " + error.statusText); }
                        //alert(error.statusText)
                    }
                });
    
            }


    Secondly, I modified the C# code of my Web Service on the Server Side App as shown below:

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public void GetBusinessInfoWithParamJSON(string symbol, string callback)
        { 
            showBusinessInfo[] result = new showBusinessInfo[] 
            { 
                new showBusinessInfo()
                {
                    symbol="MSFT",
                    name="Microsoft Corporation",
                    price= 1377.73
                },
            
                new showBusinessInfo()
                {
                    symbol="TIMBUK2",
                    name="Timbuk 2 Industries",
                    price= 1477.73
                },
            };
            
            if (symbol == "TIMBUK2" || symbol == "timbuk2")
            {
                var name = result[1].name;
                var price = result[1].price;
                var combo = symbol + ": " + name + ": " + price;
                StringBuilder sb = new StringBuilder();
                JavaScriptSerializer js = new JavaScriptSerializer();
                sb.Append(callback + "(");
                sb.Append(js.Serialize(combo));
                sb.Append(");");
                Context.Response.Clear();
                Context.Response.ContentType = "application/json";
                Context.Response.Write(sb.ToString());
                Context.Response.End();
            }
            else if (symbol == "MSFT" || symbol == "msft")
            {
                
                var name = result[0].name;
                var price = result[0].price;
                var combo = symbol + ": "+ name + ": " + price;
                StringBuilder sb = new StringBuilder();
                JavaScriptSerializer js = new JavaScriptSerializer();
                sb.Append(callback + "(");
                sb.Append(js.Serialize(combo));
                sb.Append(");");
                Context.Response.Clear();
                Context.Response.ContentType = "application/json";
                Context.Response.Write(sb.ToString());
                Context.Response.End();
                
    
            }
            else
            {
                var invalidentry = "Invalid Entry";
                StringBuilder sb = new StringBuilder();
                JavaScriptSerializer js = new JavaScriptSerializer();
                sb.Append(callback + "(");
                sb.Append(js.Serialize(invalidentry));
                sb.Append(");");
                Context.Response.Clear();
                Context.Response.ContentType = "application/json";
                Context.Response.Write(sb.ToString());
                Context.Response.End();
            
            }
         }


    That solved my problem!

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,280 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,235 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans