-1

I am trying to call a php function within a javascript function. I have attempted this via the code blow:

<?php
  function insertData(){
     //codes to insert into database
   }
?>

and a javascript like this

<script>
function goBack(){
  if (varx==confirm("Do you want to refresh page)){
    //do something
  }else{
    document.write("<?php insertData() ?>");//calls the function
  }
</script>

don't mind the punctuation, I just want to know if it's possible to achieve this ?

Samuel Hulla
  • 6,617
  • 7
  • 36
  • 70
Jay
  • 53
  • 9
  • 7
    PHP runs on server, JavaScript runs on client, they do NOT interact with each other directly. You need to submit a form or use Ajax or do something else that generates an HTTP Request. – epascarello Aug 28 '18 at 16:23
  • tnx epascarello for your answer...can i achieve same goal if i rewrite the codes in JS.? – Jay Aug 28 '18 at 16:39
  • Also for starters, you're missing an enclosing brakcet `}` . You have closed your `if..else` condition, but not your `function`. – Samuel Hulla Aug 28 '18 at 16:40
  • @Jay it's not clear what exactly you want to do. **Chances are, it is possible though**. At the very last, there is already server-sided js such as node.js (and many more) – Samuel Hulla Aug 28 '18 at 16:41
  • Possible duplicate of [What is the difference between client-side and server-side programming?](https://stackoverflow.com/questions/13840429/what-is-the-difference-between-client-side-and-server-side-programming) – Adrian W Aug 28 '18 at 18:11
  • JavaScript can not insert into your database so no it can not be done with just JavaScript. Learn the basics of Ajax to post the data to the server to be inserted. – epascarello Aug 28 '18 at 18:24
  • many tnx for all your contributions. If i make Ajax request using $.ajax, that will require me to post data in url . like data:"name=" +name+" &password=" +password, isnt this sensitive information vulnerable to attack ? anyway to secure this ? – Jay Aug 29 '18 at 15:50

1 Answers1

0

You will not be able to call a PHP function from client-side JavaScript. However you can make a HTTP request to the server using Ajax. There is a library in jQuery that allow you to make a Ajax request using $.ajax() which would be situated in your JavaScript file.

Jack Steer
  • 16
  • 2