I imagine you already have this PHP class implemented and have some method like tratarCidade()
, for example. In this case, if you are not yet working with routes and controllers (and I imagine not), there should be an action file that receives the form data and invokes your class method. We’ll call this file cidade.action.php
and he will have the following appearance:
<?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 won’t have problems handling the data on the other side with Javascript.
The first parameter of the method $.post()
must be the URL of your application where you will handle the request and invoke the method of your PHP class. In this case, the application itself cidade.action.php
:
$(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 press the send button. Note that the default action of an element input type="submit"
sends an HTTP request and causes your page to be updated. To prevent the default action of the button, your .js
could turn out 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!");
});
});
})
In this case I pass the address of the gate, but what is the parameter of the textbox? var city = $('#city'). val(); $.post("http://localhost:8080/city", Function(data, status){ Alert("Date: " + data + " nStatus: " + status); }); ; })
– Mazinho95