Solved

How can I complete an ajax post as page is rendering for a first view?

Posted on 2013-01-07
4
264 Views
Last Modified: 2013-01-14
Here is what I am doing. I need some guidance in the best way to incorporate ajax to accomplish it.

I have developed a responsive site that works well with any device, including mobile-- but I want to deliver smaller images to speed up the loading for slow/smaller screens. Thus far this works:

1) I clock the download of a small (20k) image to get a rough estimate of client's connection.

2) Using jquery, I also get the screen width.

3) I then categorize the enviorment as width+speed (i.e. smallslow, smallfast, bigslow, bigfast)

4) I store this single variable in a cookie which is available on all subsequent page calls.

5) Image tags are loaded initially without a specified src in the aspx file.
In .net code on subsequent pages, I can retrieve the cookie and set images src using this variable in a select case.

THE PROBLEM:
The very first time a client request a page from the site, this cookie is not available to the .net Page Load event. I need to pass it back to the aspx page while the page is rendering that first time view.  I am new to ajax.

Debug in js shows value is present in the ajax function and I get no error.

But debug in .net does not stop on any break points, not page_load() or the special GetSpeed() WebMethod I created (See Version 2 below). It seems my ajax call is not firing the page on the server as I expected, and I have not been able to debug it.

VERISON 1 (FAILED):
Here is the ajax call after setting cookie. Notice I am just calling the exact same url the client hit, without passing a special function with it.

Even though I coded this to pass the value of the cookie, I have been told that really, all I need is the ajax call--because cookies get passed back anyway in the http header.

<head>
 
function setcookie{...}

   var sizespeed = getCookie('cSizeSpeed');
   $.ajax({ url: "http//www.upmyscore.com/lp", data: { "sizespeed": sizespeed }, type: "POST" });
</head>

Open in new window


Here is the read in the .net page_load event:
strSizeSpeed = System.Web.HttpContext.Current.Request.Form("sizespeed")
if len(strSizeSpeed ) = 0 then
        If Not IsNothing(System.Web.HttpContext.Current.Request.Cookies("cSizeSpeed")) Then
            strSpeedSize = System.Web.HttpContext.Current.Request.Cookies("cSizeSpeed").Value
        End If 
end if

Open in new window


VERSION 2 (FAILED):
 I created a webmethod in the page and explicitly call it in the ajax post:

 var sizespeed = getCookie('cSizeSpeed');
   $.ajax({ url: "http//www.upmyscore.com/lp/lp.aspx/GetSpeed", data: { "sizespeed": sizespeed }, type: "POST" });

Open in new window



In the .net page:

    <System.Web.Services.WebMethod> _
    Public Shared Function GetSpeed()
        Dim strSpeedSize As String = ""
        If Not IsNothing(System.Web.HttpContext.Current.Request.Cookies("cSizeSpeed")) Then
            strSpeedSize = System.Web.HttpContext.Current.Request.Cookies("cSizeSpeed").Value
        End If 

Open in new window

0
Comment
Question by:hitman3030
4 Comments
 
LVL 33

Accepted Solution

by:
Slick812 earned 500 total points
ID: 38755393
greetings   hitman3030, , I have used AJAX in different ways, but I try and never use an AJAX response except for user interactions and timed page sector updates, it may not be good to do Ajax from the server for a PAGE LOADING operation, you most of the time can place the server Ajax call in the server code thats rendering the page. . OR if it depends on javascript findings (width, speed), then you can do it with just javascript, no sever code. I would think you should be able to do what you describe with out ajax, if you have the javascript for "clock the download" and "jquery, I also get the screen width" then you should change the "set images src using this javascript variable" to the Image addy for that "Size-Speed" image in the FIRST load without cookies.
I find it easier to use JS array with the changeable html (image name in this case) for the javascript to call and place for the ,


var imgAry =["smslow.jpg", "bigslow.jpg", "smsfast.jpg", "bigfast.jpg"];
the Value that you placed into the cookie with   setcookie( sizespeed  )

with sizespeed to get an integer from 0 to 3 to call the array value into the <IMG  tag

also since the cookie is availible to the server code, you can just use it to apply the Image tag in sever code, not needing ajax to update it when the page loads.

imgDOM.innerHtml = 'src="'+imgAry[aSize]+'"';

Not sure if you can apply this, but I hope it helps?
0
 
LVL 18

Expert Comment

by:Gary Davis
ID: 38756178
Verify that the cookie you created in the client is in fact sent to the server you are calling with Ajax. Cookies are only sent to domains specified within the cookie. If the cookie is not sent to the server, fix the cookie's domain or pass it as a parameter.

As far as having the client determin the size/width and then gettint the correct images, you may have to alter the image src after the page render which is certainly common in ajax/jQuery or you can have a second page called that will have the images correct from the server. In this case, the server sends the special code page to the client, the client determines the info and issues an ajax call to pass the data and then does a redirect to get the actual page. You could improve that and skip the ajax call and simply do the redirect passing the data (or cookie). The special code is an htm file with only script and would be very small and fast.
0
 
LVL 13

Expert Comment

by:darren-w-
ID: 38756220
Generally you would included the script as a file and call your code like so:

//make sure you have $
(function ($) {
//on page ready
    $(function({
        //your ajax call here
     })
})(jQuery);

Open in new window

0
 

Author Closing Comment

by:hitman3030
ID: 38777133
In the first page view, Js was the only way I could get it to work. I believe it is possible to do without a redirect by using ajax, but after 3 days...I'm defeated...may come back to it when I feel the need for pain,
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Introduction Got endorsements from your clients?  Great!  There is almost nothing better than word-of-mouth advertising.  But how can you do that on the internet?  Sure you can make a page for endorsement quotations and list them all, but who is …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

759 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

19 Experts available now in Live!

Get 1:1 Help Now