How to execute PHP file from function in JavaScript?

7

I have the following structure for registering a new MySQL database account (register.php):

<?php  
  $con = mysqli_connect("meu_host","meu_user","minha_senha","banco");
  mysqli_query($con,"INSERT INTO contas VALUES (" + $id + ", " + $pass + ", '" + $dat + "', '" + $email + "')");
  mysqli_close($con);
?>

I have the following elements on my page:

<input type="text" id="ident" />
<input type="password" id="pass" />
<input type="email" id="em" />
<input type="button" onclick="register();" value="Register" name="Reg" />

And the following script embedded in the header of the page:

<script type="text/javascript">
  function register(){
    dat = new Date();
    id = document.getElementById('ident').value;
    pass = document.getElementById('pass').value;
    em = document.getElementById('em').value;
    <!-- alert("<?PHP register(id,pass,dat,em); ?>"); -->
  }
</script>

And my question, what is the best and fastest convention to run the PHP file from a Javascript function? The commented comment was passed to me by a colleague, but it did not work.

Note: The connection to the database is working perfectly.

    
asked by anonymous 25.03.2014 / 04:09

1 answer

6

For a javascript to execute a .php it is necessary to use ajax in this example it is necessary to add the library jquery to work correctly.

This code does not work because php is processed first and then javascript. The arguments are passed in white because js will only work when the page is rendered.

alert("<?PHP register(id,pass,dat,em); ?>");

// form.html

<script type="text/javascript" src="jquery-1.10.1.js"></script>
<script type="text/javascript">
    function gravar(){

        $.ajax({
            method: "post",
            url: "gravar.php",
            data: $("#form").serialize(),
        success: function(data){
                   alert(data);
        }

    });
    }
</script>
</head>
<body>
<form id="form" action="" onsubmit="gravar(); return false;">
  id: <input type="text" id="ident" name="id" />
  pass: <input type="password" id="pass" name="pass" />
  email:<input type="email" id="em" name="email"/>
 <input type="submit">
</form>

Use preparestatements , this leaves your code more secure and less vulnerable to sql injection

gravar.php

$sql = "INSERT INTO contas VALUES (?, ?, ?, ?)";

$id = $_POST['id'];
$pass = $_POST['pass'];
$data = date('Y-m-d');
$email = $_POST['email'];


$stmt = mysqli_prepare($con, $sql);
mysqli_stmt_bind_param($stmt, "isss", $id, $pass, $data, $email);
if(mysqli_stmt_execute($stmt)){
     echo 'registros inserido com sucesso';
}else{
     echo mysqli_error($con);
}

I recommend a read on mysqli_stmt_bind_param ()

    
25.03.2014 / 04:44