2

In the below Python CGI script, I am using javascript function for changing the picture on click. But apparently it doesn't seems to work. I am following the example from w3 schools js example. So I just want to conform, is it possible to use the javascript inside Python CGI script.

If same example has to be done in Python, what should be the approach.

#!/usr/bin/env python

import cgi

print """print "Content-type: text/html; charset=utf-8
<!DOCTYPE html>
<html>
<body>
<script>
function changeImage()
{
element=document.getElementById('myimage')
if (element.src.match("bulbon"))
  {
  element.src="../pic_bulboff.gif";
  }
else
  {
  element.src="../pic_bulbon.gif";
  }
}
</script>

<img id="myimage" onclick="changeImage()"
src="../pic_bulboff.gif" width="100" height="180">

<p>Click the light bulb to turn on/off the light</p>

</body>
</html>

"""

1 Answer 1

4

Yes, you can send javascript inside the HTML via a python CGI scrpit. You have to change the initial part of the string that you are sending to:

print """Content-type: text/html; charset=utf-8\n\n
<!DOCTYPE html>
...

EDIT to add the following comments:

There were two problems in your code:

the 1st, you had to remove the part 'print "', because you were already printing a string;

the 2nd, it is a specification of CGI that it must have "\n\n" separating the header, eg. "content-type: text/html; charset=utf-8\n\n" from the following part eg. "...", (in fact as you had one implicit "\n", it would be enough to add just one more...).

Sign up to request clarification or add additional context in comments.

2 Comments

It worked, thanks a lot !! Can you please tell me what happened with changing the initial part of the string, (its significance) ?
@sarbjit There were two problems - the 1st trivial, and the 2nd difficult to discover by yourself: see the info that I've added to my answer for the details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.