Question about webpage refreshing

I use Cobra, and I have built a webserver on the basis of WouterH’s example 186 (linke: http://www.tinyclr.com/codeshare/entry/186).

I have also used the method of jasdev’s example 348 to replace the element of my html file for my webpage, and the webpage will be refreshed every 5 sec. (see picture)

I have set 1 sec for refreshimg in html file, as follow:



<head>
...............................
....................................
    <meta http-equiv="refresh" content="1" />
</head>


I find the refreshing is not good, the webpage will be refreshed completely about 5 sec, very slow. If I add some pictures for my webpage, the webpage will be very very very slow. So I don’t want to refresh complete webpage, and I only want to refresh the live data from EMX, and all lables, heads or pictures keep staying in the webpage, is it possible?

I have used red color for my live data in the picture. They are 8 temperatur inputs and 8 digital inputs.

Hey, welcome back!

You need to learn JavaScript now, to write code that just retrieves the values, then updates the value on the display. You would then need a simple url that didn’t return a full html page but just a string of your values.

@ Brett -

thank you for your answer!

I have too little experience about the JavaScript and a url for EMX. I don’t know, how I can use JavaScript and a simple url that didn’t return a full html page.

Do you remember that you gave me a webserver example(link: http://sdrv.ms/UWNIVo) a few months ago.

If it is possible, can you give me a simple start for my problem on the basis of the webserver example? I want to learn it step by step

I look forward to your answer.

If the browser client supports it, you can use the xmlhttprequest object to query a web-page for the data. For example


var request = new XMLHttpRequest();
request.open('GET', 'http://your_web_server_IP/page_with_data.htm?sensorId=_id_of_your_sensor', false);
request.send(); // false is blocking, but will be ok for test
 
if (request.status == 200) {
  document.getElementById('the_name_of_your_input_field').val = request.responseText
}

Something to that effect. Maybe this may be of help: Using XMLHttpRequest - Web APIs | MDN

If the browser client supports it you could utilize jQuery with it’s AJAX capabilities to do the job much simpler.

Here’s also a link to a somewhat old but seemingly useful .net Micro Framework AJAX implementation, perchange also of use: Michael's Blog - Ajax.NET M! - The .NET Micro Framework AJAX Library

Thanks, edited, meant ‘client’. Too tired shouldn’t post today :slight_smile:

I was having similar problem. So for know I changed the design this way.
My complete page is on HTTPServer. (Linux or Windows).
I used PHP there for login, settings logic, …
With javascript - ajax (jQuery.getJSON() | jQuery API Documentation) I only pull from microcontroller data needed:


		function GetTempHum() 
		{
			$.getJSON("IP/URL", function(data) {
				$('#idSpalnicaTemperatureValue').text(data[0]['Value']);  //write to html element temperature
				$('#idSpalnicaHumidityValue').text(data[1]['Value']);	//write to html element humidity
				var now = new Date();
				$('#idSpalnicaLastDateTime').text(now.format("d.mmm, H:MM")); //write to html element date
			});
		}

On microcontroller:

public static string ProcessGet(RequestUrl url)
        {
            switch (url["operation"].AsString())
            {
                case "GetLastTemperatureAndHumidity":
                    JsonArray data = new JsonArray();
                    data.Add(new MeasureValue(TemperatureHumidity.LastDateTimeTemperature, TemperatureHumidity.LastTemperature));
                    data.Add(new MeasureValue(TemperatureHumidity.LastDateTimeHumidity, TemperatureHumidity.LastHumidity));
                    return data.ToString();
                case "GetTemperatureAndHumidity":
                    int limit = int.MaxValue;
                    int offset = 0;
                    if (url["limit"] != null)
                        limit = url["limit"].AsInt();
                    if (url["offset"] != null)
                        offset = url["offset"].AsInt();
                    data = new JsonArray();
                    data.Add(GetTemperature(limit, offset));
                    data.Add(GetHumidity(limit, offset));
                    return data.ToString();
                case "GetTemperature":
                    limit = int.MaxValue;
                    offset = 0;
                    if (url["limit"] != null)
                        limit = url["limit"].AsInt();
                    if (url["offset"] != null)
                        offset = url["offset"].AsInt();
                    return GetTemperature(limit, offset).ToString();
                case "GetHumidity":
                    limit = int.MaxValue;
                    offset = 0;
                    if (url["limit"] != null)
                        limit = url["limit"].AsInt();
                    if (url["offset"] != null)
                        offset = url["offset"].AsInt();
                    return GetHumidity(limit, offset).ToString();
                default:
                    return "";
            }
           
        }

I am using this (http://www.tinyclr.com/codeshare/entry/282) code to return data to WebPage as ajax result.

@ harleydk -

thank you very much, I will try it.

@ andre.marschalek -

thank you for your code example!!! I will try it.

@ workhard10 - Thanks for trying my method of token replacement, but I agree that my code is VERY slow, especially if you have a lot of fields to process. The jQuery and AJAX with JSON methods mentioned in this thread are definitely the way to go.

Remember the conversation we had in your first phase of this work? The JavaScript approach here is one thing I thought you might have needed but it was too early to throw that to you to learn, hopefully everyone’s comments here will help you out.

After trying long time I feel so bad, I still don’t understand how to use the jQuery/AJAX/JSON in the webserver. I have seen a lot of examples about jQuery/AJAX/JSON, I find that maybe the “AJAX XMLHttpRequest” is what I want. but how can I write a “AJAX XMLHttpRequest” for the webserver.

Because the webserver class is not written by myself, and the webserver is from WouterH’s example 186. I don’t understand all functions of the class and I can also not develop more functions on the basis of the weserver-class.

I think, if I use AJAX XMLHttpRequest for updating parts of a web page - without reloading the whole page, I need use the “HttpRequest.cs” file of the WouterH’s example 186. Becase there are “GET” and “POST” parameter in the class. My big problem is the codes, I don’t know how can I use the classes for my destination.

until now I have only finished the webserver as follow:
the webpage will be refreshed every 1 second completely.


            using (HttpServer server = new HttpServer())
            { 
                server.AddEvent("/", new HttpServer.EventCallback(index));
                while (true)
                {
                    // Sleep for 500 milliseconds
                    Thread.Sleep(500);
                }
            }

        private static void index(object sender, HttpServer.EventCallbackEventArgs e)
        {
          string replace_string = Resources.GetString(Resources.StringResources.index);
           ...............................
           ..............................
          // read the html file as a string, the parameter in the string will be replaced 
         // T1 to T8 are from my threadloop
         string  ready_string =  stringreplace("~T1~", T1_String);
                    ready_string =  stringreplace("~T2~", T2_String);
                    ready_string =  stringreplace("~T3~", T3_String);
                    ready_string =  stringreplace("~T4~", T4_String);
                    ready_string=  stringreplace("~T5~", T5_String);
                    ready_string =  stringreplace("~T6~", T6_String);
                    ready_string =  stringreplace("~T7~", T7_String);
                    ready_string =  stringreplace("~T8~", T8_String);
           .............................................
           .............................................
          e.Response = ready_string;
          e.ResponseContentType = "text/html";

         }

index html file is as follow:


<html>
<head>
    <title>ZAGmbH TVS Home</title>
    <link rel="stylesheet" type="text/css" href="index_styling.css" />
    <meta http-equiv="refresh" content="1" />
</head>

<body>
    <h3>Temperaturinput Tabelle</h3>
        <table border="0" cellpadding="2" cellspacing="0">
        <tr><th>Temperatur Nr.</th><th>Temperatur Wert</th><th>Temperatur Nr.</th><th>Temperatur Wert</th></tr>
        <tr><td class="label">T1:</td><td>~T1~</td><td class="label">T2:</td><td>~T2~</td></tr>
        <tr><td class="label">T3:</td><td>~T3~</td><td class="label">T4:</td><td>~T4~</td></tr>
        <tr><td class="label">T5:</td><td>~T5~</td><td class="label">T6:</td><td>~T6~</td></tr>
        <tr><td class="label">T7:</td><td>~T7~</td><td class="label">T8:</td><td>~T8~</td></tr>
    </table>
</body>

</html>

Can you give me some help, how can I use the “AJAX XMLHttpRequest” in this webserver?

@ andre.m -

I want to refresh only the paramter from T1 to T16 in the index html file every 1 second, you can see my first post, I don’t want to refresh the index webpage completely every time, it is very slow.

The T1 to T16 are come from a threadloop in Programm.cs, EMX controlls a ADC with SPI and ADC connct to 16 temperature sensor.

How can I realize my destination? Can you give me a example?

@ andre.m -

thank you very much for your codes, and I have read your codes.

But I only know that you create an XMLHttpRequest Object in your example, how can can I use your codes for my index html file?

sorry that I have too little experience about the issue, can you give me more detail.

The easiest way I know is to use ajax. I like to use jquery for these minor things.

Please try this and let me know if it helps you:

  1. Load your Gadgeteer temperature code into a data.txt file for your web-server to serve. This data.txt file should be updated every 5 seconds, then, corresponding with the update of your temperature-output web page. The data.txt file must follow this exact structure:
{ "T1": 244.7, "T2": 152,"T3": -271.6,"T4": 27.5,"T5": -70.9,"T6": -255.5,"T7": 52.2,"T8": 67.6 }

That’s it - no HTML tags, no *.htm or *.html extention of the file, just call it data.txt

  1. Then place this html page for your web-server to serve:
<!DOCTYPE html>
<html>
<head>
    <title>Temperature test page</title>
    <!--Load jquery for ajax functionality-->
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">

        //        The code in our 'ready' function runs when the page has loaded
        $(document).ready(function () {

            //            We'll use the windows-object's setInterval function to run our update code very 5000 milliseconds
            window.setInterval(function () {

                //            We'll use the jquery ajax $get function to retrieve our data from the data file
                $.get('data.txt', function (data) {

                    // we'll parse the data in the data.txt file into an array...
                    var myTemperatureArray = JSON.parse(data);

                    // ... that we can then iterate in order to ...
                    $.each(myTemperatureArray, function (index) {

                        // ... update the web page itself
                        $('#' + index).html(index + ":" + myTemperatureArray[index]);
                    });

                    // plus we'll update a time-keeper to be let the user know the page data is fresh
                    $('#timeDiv').html("Temperature data updated " + new Date().toLocaleTimeString());

                }).fail(function () {

                    // oh, and let them know if a failure occured
                    $('#timeDiv').html("Failed to update temperature from data-file");
                });

            }, 5000);
        });

    </script>
</head>
<body>
    <div id="container">
        <div id="T1">
        </div>
        <div id="T2">
        </div>
        <div id="T3">
        </div>
        <div id="T4">
        </div>
        <div id="T5">
        </div>
        <div id="T6">
        </div>
        <div id="T7">
        </div>
        <div id="T8">
        </div>
    </div>
    <div id="timeDiv">
    </div>
</body>
</html>

The above html page will load and begin to poll for the data.txt file every 5 seconds, and update the webpage continously without doing a full page refresh every time. Works for me with my test data in latest Chrome and Firefox, haven’t tested in others. Let me know if it works out.

1 Like

@ andre.m -

thank you for help!

@ harleydk -

I have tried your code and it works well in Chrome, Firefox and IE. thank you very much !!

but I still have a question about the updata for the data.txt.

I have built a data.txt file and a index.html file in Resources folder. Your codes is in index.html file. I have found that the html file retrieves the txt file.

I want to replace the value “244.7”, “152”…“67.6” with my real temperature value in thread loop. I know only how to read txt file as a string from resources like as follow:


string txt_file_string = Resources.GetString(Resources.StringResources.data);

How can I write/edit the data.txt file in resources?

My project code is as follow:

The EMX read the temperature value from ADC with SPI every 20ms in a threadloop.


static void Temperature_Thread_Loop()
        {
              ..............................................
              ...............................................
              switch (ADC_channel)
                    {
                              case 1:   T1 = SPI_read(), break;
                              case 2:   T2 = SPI_read(), break;
                              case 3:   T3 = SPI_read(), break;
                              case 4:   T4 = SPI_read(), break;
                              case 5:   T5 = SPI_read(), break;
                              case 6:   T6 = SPI_read(), break;
                              case 7:   T7 = SPI_read(), break;
                              case 8:   T8 = SPI_read(), break;
                    }
                          .............................................
                          .....................................................
                          Thread.Sleep(20);

                          timer_counter++;
                          if(timer_counter==250) // updating data.txt file every 5 second
                           {
                                 timer_counter=0;
 
                                   /*I want to write some codes here for updating the data.txt file, but I don't know 
                                   how to write/edit a txt file in resources? */
                           }
                          
        }

        


        public static void Main()
        {
                 .......................................................................
                   .......................................................................
                    ........................................................................
                  using (HttpServer server = new HttpServer())
                  {
                       server.AddEvent("/", new HttpServer.EventCallback(index));
                       server.AddEvent("/data.txt", new HttpServer.EventCallback(data));
                       
                             while (true)
                             {
                                // Sleep for 500 milliseconds
                               Thread.Sleep(500);
                             }
                    }
                      
        }

                   private static void index(object sender, HttpServer.EventCallbackEventArgs e)
                    {
                       e.Response = Resources.GetString(Resources.StringResources.index);
                       e.ResponseContentType = "text/html";
                     }

                     private static void data(object sender, HttpServer.EventCallbackEventArgs e)
                     {
                           e.Response = Resources.GetString(Resources.StringResources.data);
                           e.ResponseContentType = "text/html";
                      }

            
           

@ workhard10 - Why don’t you just edit txt_file_string directly?

Managed to work it out?

If not, drop me your project at morten the-a-with-the-circle-thingy mortennorgaard dot dk and I’ll see what I can do.

@ Architect -

You are right°! It works now! thank your very much!!!

I replaced the value in data.txt one by one, I used the Replace function 8 times for value(1…8). Is it passible, that I can replace all value(1…8) in one time?

the define of data.txt is as follow:
{ “T1”: value1, “T2”: value2,“T3”: value3,“T4”: value4,“T5”: value5,“T6”: value6,“T7”: value7,“T8”: value8 }


                server.AddEvent("/", new HttpServer.EventCallback(index1));
                server.AddEvent("/data.txt", new HttpServer.EventCallback(data));

        ..................................................................
        ...................................................................
        ...................................................
        private static void data(object sender, HttpServer.EventCallbackEventArgs e)
        {
            string replace_string = Resources.GetString(Resources.StringResources.data);
            string correctString = replace_string.Replace("value1", T1_String);
                   correctString =  correctString.Replace("value2", T2_String);
                   correctString =  correctString.Replace("value3", T3_String);
                   correctString =  correctString.Replace("value4", T4_String);
                   correctString =  correctString.Replace("value5", T5_String);
                   correctString =  correctString.Replace("value6", T6_String);
                   correctString =  correctString.Replace("value7", T7_String);
                   correctString =  correctString.Replace("value8", T8_String);

            e.Response = correctString;
            e.ResponseContentType = "text/html";

        }

You can just create the string from scratch. You don’t need to find replace the old values. Just create new string from current values.