0

I am just playing around with some HTML, PHP and JS and have run into an issue. My code is:

<html>
<head>
<title> Dummy Code </title>
<script>
sendMail(){
<?php
$to      = 'example@dot.com';
$subject = 'DummyCode.com';
$message = 'This is a text message sent from DummyCode.com';
$headers = 'From: example@dot.com' . "\r\n" .
   'Reply-To: admin@dummycode.com' . "\r\n" .
mail($to, $subject, $message, $headers);
?>
}
</script>
</head>
<body>
<h1 align=center> DummyCode.com </h1>
<button type="button" onClick="sendMail()"> Send Mail! </button>
</body>
</html>

http://pastebin.com/C22UDe6J

My issue is that my JS doesn't run when I click the button, it only runs when I reload the page.

Anyone? Thanks!

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
  • 2
    there is no js in your code. its PHP – Sandeep Raju Prabhakar Feb 14 '13 at 17:59
  • 4
    I believe you are massively confused between server-side script and client-side script. – Samuel Cook Feb 14 '13 at 17:59
  • 3
    Beside the fact that you forgot to add the `function` keyoword before `sendMail() { ...`, that code will never work. You must understand js and php run at different times. Please the the possible duplicate link above. – bfavaretto Feb 14 '13 at 17:59
  • @Henry your PHP will execute as soon as you request the page. If you want to do something in PHP when a Javascript event occurs such as a button click, you can do an ajax request, or a traditional form submission. – MrCode Feb 14 '13 at 18:04
  • After some research I figured it out. Thanks. I know I am very new to this... Sorry for being so stupid. @SamuelCook –  Feb 14 '13 at 21:38

1 Answers1

3

Ok, so what happens.

You load the page. Browser sends a request to the server. On the server (remote machine) some PHP code gets executed. It produces some output (HTML) and sends it back to the browser. So when you receive HTML and it's rendered there is no PHP anymore, so clicking on the button will do nothing in your case. Just press Ctrl + U and see generated HTML, you will find nothing between sendMail(){ }.

In your case you have to issue another request to the server to execute server side script which will send an email. And it happens when you reload the page.

dfsq
  • 191,768
  • 25
  • 236
  • 258