October 11, 2012

javascript / php > Is there a way to use a regular button to submit information and call a javascript function?

Question by Edna Ramirez

I’ve built a function that rotates a picture when you click a button. I would like to tell this function how many degrees I want it to rotate with a text field or something like that and also call a function that’s being executed in php that moves a stepper motor. Is there a way to do so? I’ve tried with a submit button but it doesn’t show the animation the way I want to.

Answer by Starx

Submit button are generally used to submit forms. Although you can use them too, its not recommend. You can simply use <button /> element. And you can pass the function parameter on the onclick event handler of the button.

<button id="rotate" onclick= "rotate('35')">Rotate</button>

If you want to get value of text field and send in the form.

<button id="rotate" onclick= "rotate(document.getElementById('textboxid').value)">Rotate</button>

Demo

However, calling a function being executed over PHP is a tricky part. There are different ways you can do that:

  • Submit the form to the PHP page and assign URI parameters like page.php?function=test
  • Direct to the PHP page with passing the values in the URI parameters similar to above.
  • Use AJAX request to send and receive data.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!