Take a JS variable and move to a PHP class using Ajax with Jquery

Asked

Viewed 123 times

0

I need to create a project that consumes an api with data in json, I created the interface, but when it comes to taking the result and sending it to a class in php, but when I press the send button, nothing happens. What did I become? I saw some posts about it, but I couldn’t get out of this problem, I’m a beginner, and I wonder if anyone can help me in this issue.

<nav class="grid-12 header_menu">
   <form class="pesquisa-cidade" method="post" action="">
      <input id ="cidade" name="cidade" type="text">
      <input id="enviar" name="enviar" type="submit" class="btn">
   </form>
</nav>

Javascript

 $(document).ready(function(){
       $("#enviar").click(function(){
         var cidade = $('#cidade').val();

         $.post("",{cidade: cidade}, function(data){
           console.log("Sucesso: "+data[0]);
         },'json').error(function(){
             alert("Erro!");
         });
     });
 })

2 answers

0

The first argument of $.post is the address of your request, but you are passing only an empty string. It would have to be something like "localhost:3000/cities/". Check which port your server is on, and what your web service id is, and put it at the address.

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

0


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!");
         });
     });
 })
  • So in this case, I’m using the built-in php server, and I’m running on port 8080, it would be $.post("http:/localhost:8080/city.action.php",?

  • Because I put the project name before the file city.action and is giving error

  • If you use the built-in server, there is no need to use the project name as long as you are browsing from the project directory. I imagine you’re.

  • It is giving following error: uncaught error $post(...) and pointing the line },'json'). error(Function){

  • Change .error for .fail.

  • Stopped the error, but then it returns the error alert, I uploaded the server to the project root

  • Add header("Access-Control-Allow-Origin: *"); to his cidade.action.php, above each other header(). Maybe you are having difficulties with CORS.

  • I had created a class called Weatherclient, and made the parseCity() method and created the private variable $city, so I passed it as argument in the method and changed it in the city.action, gave the class name, but it gives the following error:Cannot read Property '0' of null, and points to the array in ajax, did not imagine that these things would be so difficult

  • Your prolema is now on the server side. The implementation of your Ajax request is done. Go through smaller snippets of code, returning value by value until you find out which variable is null and why. Good luck.

  • All right then bro, thank you so much, I’m gonna need a hug!

Show 5 more comments

Browser other questions tagged

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