Search code examples
javascriptphphtmlformssubmit-button

how to acess form with external js files? how to hide sensitive content of js from client?


I'm using emailjs to send email through my free subdomain website.There are two problems with it 1). My emailjs account-id, service-id and template-id is getting public so anybody can access it and send email through it. 2). to solve it I used following code but it steel appears in browser "inspect Element"(Developer tool).

     <?php echo "
<script>
   (function(){
      emailjs.init(my user id);
   })();
</script>" ; ?>
    <?php
      echo "<script src='js/formfilled.js'></script>"; 
    ?>

now my form submiting button is like this

    <button onclick="email();">
         Send
    </button>

now my formfill file is like this

var myform = $("form#myform");
function email(){

  var service_id = "default_service";
  var template_id = "xxxxxxxxx";

  myform.find("button").text("Sending...");
  emailjs.sendForm(service_id,template_id,"myform")
    .then(function(){ 
        alert("Sent!");
       myform.find("button").text("Send");
    }, function(err) {
       alert("Send email failed!\r\n Response:\n " + JSON.stringify(err));
       myform.find("button").text("Send");
    });
}

problem is that when I click the button rather than sending an email it reload the page . Sorry if it is too silly i am totally beginner and Thanks in advance.

UPDATE it is working if i put the code in the same file(not using external js) code:--

    <head>
              <script type="text/javascript">
   (function(){
      emailjs.init("xxxxxxxxxxxxxxxxxxxxx");
   })(); </head>
</script>
<body>
            <!-- form is here-->
<script>

var myform = $("form#myform");
myform.submit(function(event){
    event.preventDefault();

  // Change to your service ID, or keep using the default service
  var service_id = "default_service";
  var template_id = "xxxxxxxxxxxxxxxxxxx";

  myform.find("button").text("Sending...");
  emailjs.sendForm(service_id,template_id,"myform")
    .then(function(){ 
        alert("Sent!");
       myform.find("button").text("Send");
    }, function(err) {
       alert("Send email failed!\r\n Response:\n " + JSON.stringify(err));
       myform.find("button").text("Send");
    });
  return false;
});
</script>
</body>

but if i put this code in formfilled.js it is not working. what would be the reason behind it?


Solution

  • Answer: to use

     event.preventDefault(); 
    

    and loading the file before the button is loaded.