Solved

JQuery Ajax Webmethod Returning StringWriter not responsding?

Posted on 2014-03-27
12
1,235 Views
Last Modified: 2014-04-01
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
Comment
Question by:flynny
  • 7
  • 3
12 Comments
 
LVL 5

Assisted Solution

by:jayakrishnabh
jayakrishnabh earned 250 total points
ID: 39958769
please try setting size to 2147483647
0
 

Author Comment

by:flynny
ID: 39958803
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
 

Author Comment

by:flynny
ID: 39958912
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
 

Author Comment

by:flynny
ID: 39959157
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
 
LVL 33

Accepted Solution

by:
Slick812 earned 250 total points
ID: 39962652
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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:flynny
ID: 39966195
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
 
LVL 33

Expert Comment

by:Slick812
ID: 39967006
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
 

Author Comment

by:flynny
ID: 39967355
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
 

Author Comment

by:flynny
ID: 39967567
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
 
LVL 33

Expert Comment

by:Slick812
ID: 39967642
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
 

Author Closing Comment

by:flynny
ID: 39968727
got there in the end thanks guys.
0

Featured Post

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL (http://www.experts-exchange.com/articles/201/Handling-Date-and-Time-in-PHP-and-MySQL.html) several years ago, it seemed like now was a good time to updat…
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now