Wednesday, January 15, 2014

Correct way to pass data or parameters in JSON call.

Some times ago I was working on the project with JSON call and at the time my requirement to pass some data from outside by variables in the JSON. I tried various ways to pass data but did not find any success, I have also google multiple sites and blogs but not able to find the solution. finally I got the solution after some hidden trial.

There are two ways to pass the data in JSON

1- Pass data as Array

            var arr = {};
            arr.FetchXML = fetchXml;
            arr.LayoutXML = layoutXml;
            arr.EntityName = entityName;
            arr.DefaultAdvFindViewId = defaultAdvFindViewId;
            arr.ViewType = 1039;
            arr.SortCol = sortCol;
            arr.SortDescend = sortDescend;

            $.ajax({
                type: "POST",
                contentType: "application/x-www-form-urlencoded",
                datatype: "json",
                url: url,
                data: arr,
                timeout: timeoutvalue,
                beforeSend: function (XMLHttpRequest) {
                    //Specifying this header ensures that the results will be returned as JSON.
                    XMLHttpRequest.setRequestHeader("Accept", "application/json");
                },
                success: function (data, textStatus, XmlHttpRequest) {
                    PushResponseContents(iFrame, XmlHttpRequest, entityTypeId);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    //errorHandler(XMLHttpRequest, textStatus, errorThrown);
                    //alert(textStatus);
                    //alert(errorThrown);
                    doc.open();
                    doc.write("");
                    doc.close();
                    alert("Request Timeout. Please refine your search criteria");
                }
            });

2- Pass data as parameter

$.ajax({
            type: "POST",
            url: "http://" + location.hostname + "/ISV/",
            data: "{\"id\":'" + id + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                // alert(response);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //alert(jqXHR);
                //alert(textStatus);
                //alert(errorThrown);
            }

        });

Note: If this blog help to find/resolve your query then please comment.

No comments:

Loading...