Modify a web page with a request from the electric imp

hello

I like to modify a web page dynamically
( color change of the background ) with a request from the electric imp
that some refer me

I want that when I have contact " on" on an input pin
ElectricImp the changes the background color of the page of a web page

Two choices to make … You can have the agent post to the website, or the website ask the agent what the color should be.

Method 1:
The imp agent needs to POST a hex color value to a PHP script on your website.

So on your website, you have a PHP script that accepts a POSTED value and then saves that in a simple text file. Your webpage (which is also PHP), reads the value. That value would be a hex color, so it would use that as the background color.

The website background color would not change unless the page was refreshed. Otherwise, you’ll need some javascripting that continuously looks for a change.

Method 2:
Likewise, you could have your PHP script /javascripting ask the agent what color it should be. So basically, doing what you want in reverse. If someone is not viewing the website, why have the agent send information? Sort of like if a tree falls in a forest, does it make a noise? I would have the web page (AJAX) ask the agent what color it should be.

Mixing javascripting with PHP, a method called AJAX, would be something you may look into via Google.

Yes this is certainly possible and there are a couple of ways to do this depending on what you mean by “with a request from electric imp that some refer me”. Please explain what you are trying to do.

Assuming you plan just to use the agent URL rather than a separate website / webserver, then here is an example using just javascript within the html page.

In this example I am using one of the standard Bootstrap templates to handle my page layout etc. In this example I have also used jquery UI animate to create a slight delay in the colour change for visual impact.

Agent Code:
`
// This file is licensed under the MIT License
// http://opensource.org/licenses/MIT

function MainPage()
{
local html = @"










        <title>Imp Background Colour Change Example</title>
    
        <!-- Bootstrap core CSS -->
    	<link rel='stylesheet' href='https://netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css'>
    	<style>
    		/* Copy of bootstrap jumbotron-narrow css */
    		body { padding-top: 20px; padding-bottom: 20px; }
    		.header, .footer { padding-right: 15px; padding-left: 15px; }
    		.header { padding-bottom: 20px; border-bottom: 1px solid #e5e5e5; }
    		.header h3 { margin-top: 0; margin-bottom: 0; line-height: 40px; }
    		.footer { padding-top: 19px; color: #777; border-top: 1px solid #e5e5e5; }
    		@media (min-width: 768px) { 
    			.container { max-width: 730px; } 
    		}
    		.container-narrow > hr { margin: 30px 0; }
    		.jumbotron { text-align: center; border-bottom: 1px solid #e5e5e5; }
    		.jumbotron .btn { padding: 14px 24px; font-size: 21px; }
    		@media screen and (min-width: 768px) {
    			.header,.footer { padding-right: 0; padding-left: 0; }
    			.header { margin-bottom: 30px; }
    			.jumbotron { border-bottom: 0; }
    		}
    	</style>
    	<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'></script>
    	<script src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js'></script>
    	<script src='https://netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js'></script>
    
      </head>
    
      <body>
    
        <div class='container'>
          <div class='header clearfix'>
            <h3 class='text-muted'>Button Press Colour Change Example</h3>
          </div>
    
          <div class='jumbotron' id='effect'>
            <h1>Electric Imp Controller</h1>
            <p class='lead'>Click button to change GPIO pin 1 output on Imp.</p>
            <p><button class='btn btn-lg btn-default' id='ImpBtn'>Turn it ON</button></p>
    		<p><span id='ImpUpdate'></span></p>
          </div>
    
          <footer class='footer'>
            <p>&copy; MIT License 2015</p>
          </footer>
    
        </div> <!-- /container -->
    	
    	<script>
    	$(function() {
    		var state = true;
    		var btnVal = 0;
    		$('#ImpBtn').click(function() {
    		    if ( state ) btnVal = 2;
    		    else btnVal = 1;
    			$.post(document.URL, {btn:btnVal}, (function(data) {
    			    if (data == 'BTN_ON') {
        				$('#ImpUpdate').html('<small>GPIO pin 1 is now ON</small>');
        				$('#ImpBtn').text('Turn it OFF');
        				$('#effect').animate({
        					backgroundColor: 'green',
        					color: '#fff'  }, 300 );
    			    }
    			    if (data == 'BTN_OFF') {
        				$('#ImpUpdate').html('<small>GPIO pin 1 is now OFF</small>');
        				$('#ImpBtn').text('Turn it ON');
        				$('#effect').animate({
        					backgroundColor: 'red',
        					color: '#fff'  }, 300 );
    			    }
    			}))
    			.fail(function(data) {alert('ERROR: ' + data.responseText);});
    		    state = !state;
    		});
    	});	
      </script>
      </body>
    </html>
";

return html;

}

function httpHandler(request,response) {
try
{
local method = request.method.toupper();
local DeviceConnected = true;

    response.header("Access-Control-Allow-Origin", "*");

    if (method == "POST") 
    {
        local data = http.urldecode(request.body);
        if ("btn" in data) {
            if (data.btn == "2") {
                server.log("html request to turn button ON");
                device.send("setPin", 1);
                response.send(200,"BTN_ON");
            }
            else if (data.btn == "1") {
                server.log("html request to turn button OFF");
                device.send("setPin", 0);
                response.send(200,"BTN_OFF");
            }
        } else server.log("unknown data received");
    }
    else
    {
        response.send(200, MainPage());
    }
}
catch(error)
{
    response.send(500, "Internal Server Error: " + error);
}

}

/* REGISTER HTTP HANDLER -----------------------------------------------------*/
http.onrequest(httpHandler);
`

and here is the basic device code for the example
`
// This file is licensed under the MIT License
// http://opensource.org/licenses/MIT

imp.setpowersave(true);

function PinUpdate(s) {
hardware.pin1.write(s);
if (s) server.log(“GPIO pin1 set to HIGH”);
else server.log(“GPIO pin1 set to LOW”);
}

hardware.pin1.configure(DIGITAL_OUT);

agent.on(“setPin”, PinUpdate);
`

This was a bit of experimentation on the fly…

Here is the form post method without any javascript using the agent URL. Device code as above. This method checks pin 1 output status before loading the webpage.

Here is the agent code:

`
// This file is licensed under the MIT License
// http://opensource.org/licenses/MIT

btnState <- 0;

function MainPage(bgrndColor, btnText, Statmsg)
{
local html = @"










        <title>Imp Background Colour Change Example</title>
    
        <!-- Bootstrap core CSS -->
    	<link rel='stylesheet' href='https://netdna.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css'>
    	<style>
    		/* Copy of bootstrap jumbotron-narrow css */
    		body { padding-top: 20px; padding-bottom: 20px; }
    		.header, .footer { padding-right: 15px; padding-left: 15px; }
    		.header { padding-bottom: 20px; border-bottom: 1px solid #e5e5e5; }
    		.header h3 { margin-top: 0; margin-bottom: 0; line-height: 40px; }
    		.footer { padding-top: 19px; color: #777; border-top: 1px solid #e5e5e5; }
    		@media (min-width: 768px) { 
    			.container { max-width: 730px; } 
    		}
    		.container-narrow > hr { margin: 30px 0; }
    		.jumbotron { 
    		    text-align: center; 
    		    border-bottom: 1px solid #e5e5e5; 
    		    background-color:" + bgrndColor + @";
    		    color: white;
    		}
    		.jumbotron .btn { padding: 14px 24px; font-size: 21px; }
    		@media screen and (min-width: 768px) {
    			.header,.footer { padding-right: 0; padding-left: 0; }
    			.header { margin-bottom: 30px; }
    			.jumbotron { border-bottom: 0; }
    		}
    	</style>
    	<script src='https://netdna.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js'></script>
    
      </head>
    
      <body>
    
        <div class='container'>
          <div class='header clearfix'>
            <h3 class='text-muted'>Button Press Colour Change Example</h3>
          </div>
    
          <div class='jumbotron' id='effect'>
            <h1>Electric Imp Controller</h1>
            <p class='lead'>Click button to change GPIO pin 1 output on Imp.</p>
            <form method='POST'>
            <p><button class='btn btn-lg btn-default' type='submit' name='SubmitBtnRequest'>Turn it " + btnText + @"</button></p>
            </form>
    		<p><span>" + Statmsg + @"</span></p>
          </div>
    
          <footer class='footer'>
            <p>&copy; MIT License 2015</p>
          </footer>
    
        </div> <!-- /container -->
    	
      </body>
    </html>
";

return html;

}

function httpHandler(request,response) {
try
{
local method = request.method.toupper();
local DeviceConnected = true;

    response.header("Access-Control-Allow-Origin", "*");

    if (method == "POST") 
    {
        local data = http.urldecode(request.body);
        if ("SubmitBtnRequest" in data) {
            btnState = !btnState;
            if (btnState) {
                server.log("html request to turn button ON");
                device.send("setPin", 1);
                response.send(200, MainPage("green", "OFF", "GPIO pin 1 is ON"));
            }
            else {
                server.log("html request to turn button OFF");
                device.send("setPin", 0);
                response.send(200, MainPage("red", "ON", "GPIO pin 1 is OFF"));
            }
        } else server.log("unknown data received");
    }
    else
    {
        if (btnState) 
            response.send(200, MainPage("green", "OFF", "GPIO pin 1 is ON"));
        else 
            response.send(200, MainPage("red", "ON", "GPIO pin 1 is OFF"));
    }
}
catch(error)
{
    response.send(500, "Internal Server Error: " + error);
}

}

function DeviceConnect_Handler() {
server.log("Device connected to agent - setting pin 1 output to " + btnState);
device.send(“setPin”, btnState);
}

/* REGISTER HTTP HANDLER -----------------------------------------------------*/
http.onrequest(httpHandler);
device.onconnect(DeviceConnect_Handler);

`

hey guys kind of related topic, when I try to write the html code into a variable it doesnt highlight in green the whole html code (see image) am I missing something here?

not sure what mean exactly, but looking at your image of the html you need to be careful with using double quotes (") inside your variable html variable (local html = @"… your html code…":wink: as you need to use single quotes (’) where possible. Hence your line: <script src = "http://ajax… has double quotes which would cause problems. Use single quotes.

Otherwise yes when it comes to html, the IDE does not following colour coding correctly all of the time.

Thanks for the input, i found out the error I was getting was due the string being way too long.

thank you for your help I’ll test that.
my real project is to show in real time on a website the values ​​x, y, z of an accelerometer

I tested your example , though, it is the opposite that I wish
when contacted on 1 pin , I modify a page on a site hosted elsewhere

As @mlseim says, @baudetd, you’ll need to write agent code that contact the site hosted elsewhere. You’ll need to have that site set up with a script that will react to, for example, the agent PUTing either the colour values you want the site background to be or just a signal value to tell the site to change its background. Either way, the site needs code to read the info from the agent and react accordingly.

Your device code is basically

`pin1.configure(DIGITAL_IN, function () {
    agent.send("pin.state.change", true)
})`

and your agent code

`device.on("pin.state.change", function () {
    local backGndColour = http.jsonencode( { "red" : 255, "green" : 0, "blue" : 255 } )
    local signalColour = http.put("YOUR_SITE_URL", { "Content-Type" : "application/json" }, backGndColour)
    local repsonse = signalColour.sendsync()
})`

You’ll then need a script running on the site to decode the colour data and update the page’s HTML. You could probably combine both these functions using something like Ajax, but it’s not my area of expertise.