Javascript can not directly run a PHP function, you can instead call a PHP file or snippet of PHP with these two methods:
You have two options, either you can make an onclick function calling an AJAX request, which will run a PHP file, or you can create a form and skip the onclick entirely. Here are demos of the two:
AJAX Method:
$("button").click(function(){
$.ajax({url: "myFunction.php", success: function(result){
alert("Success")
}});
});
Read about AJAX requests here
Here is the form method:
<?php
if(isset($_POST['submit'])) {
// Do some code here, as the button was clicked
// in this case we will run criarProduto()
criarProduto();
}
?>
<form action="" method="post">
<input type="Submit" name="submit"></input>
</form>
Note that detecting whether a POST request was received is important, as that is how you differentiate between a form being sent, and a normal user loading the page. Also note that the action=”” is blank as we want to run the page they are currently on, if you want the PHP from another file you would enter the url path there instead.
If you choose the PHP method, your page will reload, if you choose the AJAX method a request will be made in the background and the page won’t be reloaded, either method is fine.
Also a reminder, your code is open to SQL Injections, it is never a good idea to directly input variables into your SQL Query, you should instead use prepared statements, you can learn how to do those here: Prepared Statements
Im doing a school project that is basicly a website in php to create a product in my database.
the only problem i am having is to find a way to execute the php function by the button “onclick”.
Note: sorry about the portuguese variable names(other request by the teacher)
there is the code:
<?php
function criarProduto($descricao,$preco){
$connection = mysqli_connect("localhost", "root", "", "lojadb","3308");
if(!$connection){
die("ERROR: Could not connect. " . mysqli_connect_error());
echo "<center><h1>Erro na conexão à base de dados</h1><center>";
}
$sql = "INSERT INTO produtos(descricao, preco) VALUES ('" . $descricao . "', " . $preco . ")";
$results = mysqli_query($connection, $sql);
if (mysqli_num_rows($results) > 0) {
$row = mysqli_fetch_array($results);
$produto = new Produto($row);
}
else {
echo "<center><h1>Erro na agregação de dados na base de dados</h1></center>";
}
mysqli_close($connection);
}
//meter a verificação de texto(se tem alguma coisa escrita)
echo "<center><h1>Criar produto</h1></center>";
echo "Descrição: <input type='text' name='descricao'>";
echo "<br>Preço: <input type='text' name='preco'>";
echo "<input type='button' value='Gravar'></input></center>";
?>
i did that and the code from the function is running whenever i refresh the page(it was supposed to way for the form to be submited)
You must remember that the function will run whenever you run the page UNLESS you add the if statement checking if the request includes POST data. If the POST data is present, you know that the form was submitted, that is the key part
Sorry, im not sure what you mean, do you mean pass the input variable into a function in a class?