How to run PHP file from Javascript function?

Asked

Viewed 25,983 times

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 next script embedded in the header 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 comado was passed to me by a colleague, but it didn’t work.

Note: the connection to the database is working perfectly.

1 answer

6


For a javascript to run a . php it is necessary to use ajax in this example it is necessary to add the library jquery to function properly.

This code does not work because php is processed first and then javascript. Arguments are passed blank because js will only work when the page is rendered.

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

//html form.

<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>

Utilize preparestatements, this makes your code safer and less vulnerable to sql Injection

write 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);
}

recommend a read on mysqli_stmt_bind_param()

  • How could you post the current system date instead of one defined in form?

  • 1

    +1 - it would be interesting to put an example with vanilla since the question has no jQuery tag

  • I did exactly as in the reply, and the record was not entered. Once the page is updated, I cannot see the results of the Echos for debug. Idea?

  • @Guill, if you use firefox install a javascript Debugger like firebug to see the return of ajax. In Alert nothing appears?

  • @lost Chrome usage. Nothing appears. Just refresh the page and display the form values in the url, including the password... One detail: in the database my password field is of the whole type, so I replaced "isss" with "iiss". I did it correctly?

  • Press F12 on Chrome, and run the code again, see if an error appears on the console.

  • "GET http://giproductions.byethost24.com/jquery-1.10.1.js 404 (Not Found)" It looks like I need to import the jQuery lib to the FTP server.

  • I imported the jQuery and it worked. Like the tag jQuery is not part of the question, I ask you to write in the answer, that you need to have the file "jquery-1.10.1.js" in the page folder.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.