-3

I had a problem.I wanna do a query only when i click a button but without click it did the query the code is:

<html>
<head>
   <title>prova del metodo post tramite javascript</title>
   <script>
   function scriviSQL(){

    document.write("<?php   
    $con = mysql_connect('localhost','root');
    if (!$con)
    {
        die('Could not connect: ' . mysql_error());
    }

    mysql_select_db('provadidb', $con);

    $sql = 'INSERT INTO provatab (cognome,nome) VALUES("provdicognome","provadinome");';    
    mysql_query($sql,$con);

    mysql_close($con);  
    ?>");

   }
  </script>

    <button id="conferma" onClick="scriviSQL();">Continua</button> 

i tryed to put it in body or head i had the same problem, i tryed to create a function with php too but nothing... sorry for my bad english..

Bhumi Shah
  • 9,323
  • 7
  • 63
  • 104
d0xzen
  • 181
  • 1
  • 1
  • 9
  • dude what type of code is this? You can not code like this. You can not put docoument.write – pregmatch Apr 28 '14 at 22:27
  • You need to invsetigate a bit more about what is server-side and what is client-side scripting. After that, a bit of basic concepts of AJAX (Asynchronous Javascript And XML, althought today JSON is mostly preferred, AJAX kept it's name as is). Server-side languages cannot be rendered in browser nor interact with client-side languages. Not even server-side languages can interact among themselves! Sorry, since I hate downvoting. But read this: http://programmers.stackexchange.com/questions/171203/what-are-the-difference-between-server-side-and-client-side-programming – Luis Masuelli Apr 28 '14 at 22:35

1 Answers1

0

Web page javascript runs in the browser. It does not run on the server.

PHP runs on your server. It does not run in the browser.

Some PHP may run at the time the web page is requested in order to populate some data into the web page, but once the web page has been served to the browser, there is no more PHP. Your particular PHP is running when the web page is served which is why it runs immediately and doesn't wait for the click.

Because of the way this all works, you cannot use the construct you're trying to use where you are trying to execute PHP from the browser.

If you want to do a query on your server from a javascript function in the web page like your scriviSQL() function, then you need to use an Ajax call to actually call your server and your server will have to be ready to receive and process that request.

I'd suggest you do some Googling for Ajax as you will find a ton of useful references. You can start with the Wikipedia article on Ajax which has a code example with javascript in the web page and PHP on the server.

jfriend00
  • 683,504
  • 96
  • 985
  • 979