• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1385
  • Last Modified:

JQuery Ajax Webmethod Returning StringWriter not responsding?

Hi all,

I have an ajax method which loads a page from my db and displays it in a modal window.

Now the AJAX call works fine if I add some small html e.g. <div> test </div>

However, it is constantly returning a 500 error which I try and return alot of text.

webmethod
    [WebMethod]
    public string GetPageControl(int pageID)
    {
        try
        {
            Page page = new Page();
            PageUserControl control = (PageUserControl)page.LoadControl(BASE_PATH + "Page.ascx");
            control.CurrentPage = pageID;
            HtmlForm form = new HtmlForm();
            form.Controls.Add(control);
            page.Controls.Add(form);
            StringWriter writer = new StringWriter();
            HttpContext.Current.Server.Execute(page, writer, false);
            return writer.ToString();
        }
        catch (Exception ex)
        {
            //log the error here
            return string.Empty;
        }        
    }

Open in new window


function loadControl(pageID, control) {

    var jsonObject = {};
    jsonObject["pageID"] = pageID;

    return $.ajax({
        type: "POST",
        url: "SignupServices.asmx/GetPageControl",
        data: JSON.stringify(jsonObject),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (r) {
            $alert('success');
            $(control).html(r.d);
            $(control).show();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('oh oh error');
            alert(xhr.status);
            alert(thrownError);
        }
    });

    return false;
}

Open in new window


So I added the following to my web.config;

  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="400000" />
      </webServices>
    </scripting>
  </system.web.extensions>

Open in new window


this has stopped the 500 error, but now I dont get a response at all? i.e. neither error nor success is being fired?

The file size is 106kb (i pasted and saved the result to a txt file).

any ideas?
samplewriter.txt
0
flynny
Asked:
flynny
  • 7
  • 3
2 Solutions
 
jayakrishnabhCommented:
please try setting size to 2147483647
0
 
flynnyAuthor Commented:
Hi thanks for your comment.

I have changed to the following;

  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="2147483647" />
      </webServices>
    </scripting>
  </system.web.extensions>

Open in new window


the web method fires and i can move through to the return for the string, and then it just moves back to the page, neither success or error is fired.

is there anything further I can do to debug?
0
 
flynnyAuthor Commented:
to try and get more info I now have the following for my ajax call;

function loadControl(pageID, control) {

    var jsonObject = {};
    jsonObject["pageID"] = pageID;
    var loadingHTML = "<div class='modal'><image ID='imgUpdateProgress' src='./images/loading.gif' class='loading-image' /><span ID='ModalLoadingMessage' class='loading-message'>Please wait, applying the party magic...</span></div>";

    return $.ajax({
        type: "POST",
        url: "SignupServices.asmx/GetPageControl",
        data: JSON.stringify(jsonObject),
        contentType: "application/json; charset=utf-8",
        dataType: "html", //also had 'json' here
        timeout: 6000,
        beforeSend: function () {
            $(control).html(loadingHTML);
            $(control).show();
        },
        success: function (r) {
            $alert('success');
            $(control).html(r.d);
            $(control).show();
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert('oh oh error');
            alert(xhr.status);
            alert(thrownError);
            $(control).hide();
        }
    });

    alert("Finished Ajax");
    return false;
}

Open in new window


now when running the loading modal appears and then disappears with no further textbox output.

If I hold a breakpoint on the webmethod return I can get the ajax timeout to then fire, in which case it will fire the error textbox outputs.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
flynnyAuthor Commented:
HI,

to add I have changed to pass a small string back now and this is now not returning;

    [WebMethod]
    public string GetPageControl(int pageID)
    {
        try
        {
            Page page = new Page();
            PageUserControl control = (PageUserControl)page.LoadControl(BASE_PATH + "Page.ascx");
            control.CurrentPage = pageID;
            HtmlForm form = new HtmlForm();
            form.Controls.Add(control);
            page.Controls.Add(form);
            StringWriter writer = new StringWriter();
            HttpContext.Current.Server.Execute(page, writer, false);
            //return writer.ToString();
            return "Test title";
        }
        catch (Exception ex)
        {
            //log the error here
            return string.Empty;
        }        
    }

Open in new window


note, the webmethod IS firing and returning the 'Test Title' string.
0
 
Slick812Commented:
greetings  flynny, , I may or may not can help, but In my use of the jquery $.ajax({ , I have had problems if ever I Change the -
contentType:

in an Ajax POST, the type:POST will set the default for contentType: to
default: 'application/x-www-form-urlencoded; charset=UTF-8'
Which WORKS, so unless you know what you are doing! and have a very special REASON, do not put in the contentType: in any POST ajax request.
 ALSO if you set the - dataType: "json",  - This will fundamentally ALTER the way jquery uses the Ajax return, the ONLY time it will succeed if if the response return is in the StringJSON format like -
{"name":"Pat","age":21}
other wise it will error out with a parse error, again you need to know what you are doing if you set the dataType: "json", you DO NOT need to set the contentType:  to json is you set the dataType: to json, they are NOT related settings, and adjust different things in the ajax transaction

You have this -
data: JSON.stringify(jsonObject),

this does not seem a way to set a POST data string? I would think that this -
data: {pageID:pageID1},
// can NOT use a var as pageID so change to pageID1 to avoid confusion

might work better?


here is some code I use for a successful jquery AJAX -
var j = "listUsers";

  var ajxOptions = {
    url: "jqy-ajax1.php",
    type: "POST",
    data: {job:j,user:"Pat"},
    dataType: "text",
    timeout: 3500}

// get the Jquery AJAX in aj with $.ajax( )
  var aj = $.ajax(ajxOptions);
        
// the aj.done( ) method is the successful return of AJAX
  aj.done(function( received ) {
    $('#ajaxRe').html(received);
	});

// the aj.fail( ) method is the UNsuccessful (error) return of AJAX	
  aj.fail(function(xhr, error1, err) {
// xhr is the XMLHttpRequest Object
// error1 is the Jquery guess at what the error was
// err is the reason for jquery ERROR
  if (xhr.status==404) alert("ERROR from Ajax as '404 status' the "+ajxOptions.url+
  " page was NOT on Server, \nCan NOT recover from this ERROR, This operation is NOT available!");
  else {
    alert("Ajax ERROR = \""+error1+"\", with server Status: "+xhr.status+", post-URL: "+ajxOptions.url+
	", \npost-Data: "+ajxOptions.data+", \nerror because: "+err);
    if (aj.responseText) {
    $('#ajaxRe').html(aj.responseText); 
    }else $('#ajaxRe').html("Ajax Received Text is empty");
  }
  });

Open in new window

As far as I know, there are few, if any limits on the amount of Text data that ajax can return, 106 Kb should be no problem at all, IF it is parsed correctly for real time HTML, as making your form -
<form name="ctl00" method="post" action="../SignupServices.asmx" id="ctl00">

I have removed the \ for the ", but if these are still in the string for HTML from the ajax, , then you have BIG PROBLEMS
0
 
flynnyAuthor Commented:
Hi Slick,

First of all thanks for the supply.

Currently I am calling the webmethod.

The webmethod is firing and the data is being passed with no problems.

The issue is, when I return the data string, the ajax call is not picking it up?

It was working initially if I sent a small string, but it has stopped working completely now and is not firing error OR success on the webservice completing.

I have other working ajax calls on my site, but these are simply reutrn bools or IDs, but this shows that the web.config additions are not stopping any ajax calls i suppose.

Is there any way I can debug or find out why the jquery is not receiving the data return
0
 
Slick812Commented:
Sorry, I have never seen or heard of an AJAX request working on "small string" and Not working on a larger data string? ? ? You should ALWAYS, I mean ALWAYS!, set an ajax Timeout -
timeout: 3500}

of some appropriate amount, my default is 3 and a half seconds =3500 .
IF you send a request to server and the server refuses to respond, then the Ajax error function will never be called, it will continue to wait Forever, to receive the ajax response. IF you set a timeout then the error will show after the timeout period.

For all I know about the jquery Ajax, if there is ANY server response, then some response function is called. As I said, if you set the -
dataType: "json"

then the success will ONLY happen if the response if in the JSON string format, but the error function is called regardless. You say you have tried the other way a "plain", and that did not work either? ?
I would think this is some server setting problem, for the larger string response, than a browser problem, as noted earlier, this ajax thing in modern browsers WORKS, and WORKS well.
just a note? there are reported problems with IE ver11 and older versions of jquery. you should maybe use the latest jquery ver-
jquery/1.11.0/jquery.min.

NOT sure what to suggest? if it might be the jquery ajax setup (highly unlikely), but you might try to do a javascript -
xmlhttp=new XMLHttpRequest();
ajax functioning without any jquery?
0
 
flynnyAuthor Commented:
Slick,

OK, to point out neither success or error is firing at all for big or small string (i mentioned this in my previous post but reading back it does seem a bit ambiguous).

Also, I have used the timeout feature (mentioned in my 2014-03-27 at 13:55:45 post).

As I mentioned there, if I put a break point in the webmethod I can get the error to fire based on the timeout.

The strange issue is that the data doesn't seem to be returning to the method on the front page??

Hope this is clear, Any ideas how I could debug to see if any error are being thrown?
0
 
flynnyAuthor Commented:
Hi Guys,

just seen its a really idiotic error.

there is a $ preceeding the success alert. Removing this solves the callback and it reutrns successfully. The error console in chrome helped detect this error (for some reason I just didnt see it!).

The issue I am having now is the fact the loaded usercontrol (which is added to the div is being lsot immeadiately as the page_load method of the aspx is over writing).
0
 
Slick812Commented:
Good deal, a single $ was the breaker,
you say - loaded usercontrol  is over writing ? ?
I can not help you with is at all, sorry, but for me many things in code are because I have a single misplaced .  ,  $  ' or ;     in the code work, not enough to prevent the code from being used, but enough to get the wrong result. Hope you can get someone else to guide you for the  loaded usercontrol  problem.
0
 
flynnyAuthor Commented:
got there in the end thanks guys.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 7
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now