0

I make a Json call to an ashx handler like this:

    attributes = $("#pageHtmlTag").attr("class").trim();
urlToHandler = 'JSonTestHandler.ashx';
jsonData = '{' + attributes + '}';

$.ajax({
    url: urlToHandler,
    data: jsonData,
    dataType: 'json',
    type: 'POST',
    contentType: 'application/json',
    success: function (data) {
        setAutocompleteData(data.responseDateTime);
        $("body").add("<div>" + data.toString() + " </div>").appendTo(document.body);
        alert("grate suceees");
    },
    error: function (data, status, jqXHR) {
        alert('There was an error.' + jqXHR);
    }
}); // end $.ajax   

I receieve it and proccess it. I also want to send back some HTML to be displayed but i dont know how to send html back to the Jscript.

ashx:

    string jsonData = new StreamReader(context.Request.InputStream, System.Text.Encoding.UTF8).ReadToEnd();

.............................

        var testResultReportString = testResultReport.GetReportHtml();

        var serializer = new JavaScriptSerializer();
        var jSonTestResultReport = serializer.Serialize(testResultReportString);

        context.Response.Write(jSonTestResultReport);

So the question is. How do i return data to the Ajax calls success function?

3 Answers 3

0

You could return your data as JSON object:

var outputObject = "{ html = '" + jSonTestResultReport  + "' + someOtherData = ... + "}";
context.Response.Write(outputObject);

and access them in success function like this:

data.html and data.someOtherData
Sign up to request clarification or add additional context in comments.

2 Comments

Its not working. I get the error in a Alert popoup: Syntax error. Unexpected token = The output i send back is: { "resultReport" = " <li style="color:green;">js</li> " }
Oh i figured it out. I used an = instead of an :
0

In application i am useing like this it's below i am showing all me state data with country id and that data bind to the state dropdownlist like this ..

StateData objStateData = new StateData();
            LMGDAL.db_LMGEntities dbData = new db_LMGEntities();               
            var data = (from con in dbData.tblStates
                        where con.State_CountryID == ID
                        select new StateData
                        {
                            StateID = con.StateID,
                            StateName = con.StateName
                        }).ToList();
            return data.ToArray(); 

and also create a new class in inside that .ashx file

[Serializable]
    public class StateData
    {
        public int StateID { get; set; }
        public string StateName { get; set; }
    }

and in my form

$("#ddlCountry").change(function () {
            var countryID = $("#ddlCountry").val();
            $.ajax({
                type: "POST",
                url: "JsonData.asmx/GetStateByCountryID",
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: '{ID:"' + countryID + '"}',
                success: function (msg) {
                    var data = msg.d;
                    var stateData = "";
                    $.each(data, function (index, itemdata) {
                        stateData += "<option  value='" + itemdata.StateID + "' > " + itemdata.StateName + " </option>";
                    });
                    $("#ddlState").empty();
                    $("#ddlState").append("<option value='0'>-Select State-</option>");

                    $("#ddlState").append(stateData);
                },
                error: function () {
                    alert('Faild To Retrieve States.');
                }
            });
        });

i think this will help you.....

Comments

0

You can't return data returned by an AJAX call because your data is not available immediately after the call to $.ajax as it is asynchronous. What you can return is a promise of a data returned by an AJAX call. A promise is a nice abstraction for functions to say: I can't return you the data because I don't have it yet and I don't want to block and make you wait so here's a promise instead and you'll be able to use it later, or to just give it to someone else and be done with it (Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patterns in JavaScript). For example, instead of:

$.ajax({
     url: urlToHandler,
     data: jsonData,
     dataType: 'json',
     type: 'POST',
     contentType: 'application/json',
     success: function (data) {
         setAutocompleteData(data.responseDateTime);
         $("body").add("<div>" + data.toString() + " </div>").appendTo(document.body);
         alert("great success");
     },
     error: function (data, status, jqXHR) {
         alert('There was an error.' + jqXHR);
     }
 }); // end $.ajax  

you can return the return value of your $.ajax(...) call by writing your Ajax function like:

function testResultReportAjax() {
    return $.ajax({
        url: urlToHandler,
        data: jsonData,
        dataType: 'json',
        type: 'POST',
        contentType: 'application/json',
        error: function (data, status, jqXHR) {
            alert('There was an error.' + jqXHR);
        }
    });
}

You get your promise by way of

var promise = testResultReportAjax();

which you can then use as an argument in function calls and use your data that is returned by the AJAX call:

promise.success(function (data) {
   alert(data);
});

You can view a simple DEMO here. See this answer for a better explanation if needed.

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.