I imagine you already have this PHP class implemented and that has some method like tratarCidade()
, for example. In this case, if you are not already working with routes and controllers (and I imagine not), there must be an action file that receives the form data and invokes the method of its class. We'll call this file cidade.action.php
and it looks like this:
<?php
include('MinhaClasse.php');
$cidade = $_POST['cidade'];
$objeto = new MinhaClasse();
$resposta = $objeto->tratarCidade($cidade);
header("Access-Control-Allow-Origin: *");
header('Content-type:application/json;charset=utf-8');
echo json_encode($resposta, JSON_UNESCAPED_UNICODE);
?>
The first header allows requests to be made from any source. Below, we're printing the answer in JSON so you do not have trouble handling the data on the other side with JavaScript.
The first parameter of the $.post()
method should be the URL of your application where you will process the request and invoke the method of your PHP class. In this case, the cidade.action.php
itself:
$(document).ready(function(){
$("#enviar").click(function(){
var cidade = $('#cidade').val();
$.post("http://localhost/seuprojeto/cidade.action.php",
{cidade: cidade}, function(data){
console.log("Sucesso: "+data[0]);
},'json').fail(function(){
alert("Erro!");
});
});
})
You also said that nothing happens when you hit the send button. Note that the default action of a input type="submit"
element sends an HTTP request and causes your page to be updated. To prevent the default action of the button, your .js
might look like this:
$(document).ready(function(){
$("form").submit(function(e){
e.preventDefault();
});
$("#enviar").click(function(){
var cidade = $('#cidade').val();
$.post("http://localhost/seuprojeto/cidade.action.php",
{cidade: cidade}, function(data){
console.log("Sucesso: "+data[0]);
},'json').fail(function(){
alert("Erro!");
});
});
})