Return of Ajax to PHP

Asked

Viewed 55 times

-1

I do not know if it is possible, because I know that javascript is client and PHP is server. But I would like to take the return that comes from ajax (after running PHP and returning) and store it in a PHP variable. Example below;

<script>
    $.ajax({

        url: 'assets/php/advantage-club.php',
        type: 'POST',
        dataType: 'html',
        data: {
            "pass": "3d1fa6s0df51as8das6d2f1as036f15as8df90"
        }

    }).done(function(r) {
        AQUI EU TENHO O RETORNO,
        QUERIA COLOCAR O RETORNO
        NUMA VARIAVEL DO PHP PARA TRABALHAR ABAIXO
    });
</script>

<?php
    echo '<pre>';
        var_dump($r);
    echo '</pre>';  
?>

Would this be possible?

  • Oloco, my ! Why this need to make this display in PHP ?

  • curiosity, what I need I can do via for() and display below. But I was curious to understand how I can’t play the value for PHP again. @Gatodeschrödinger

  • I answered below... but if you need in PHP to call another php page to work with the result of this second page, then instead of using ajax, you use Curl. Check on your server or wampp, xampp for life if the Curl extension is active.

1 answer

0

That is not possible.

The PHP runs on the server and returns a HMTL.

The ajax however it runs in the browser through javascript. So your browser cannot dynamically assign a value to a variable PHP.

As you may know, the call ajax sends an HTTP request to your page assets/php/advantage-club.php and in your case is returning a content HTML.

What you can do is, instead of returning a HTML, change the dataType for JSON and on your page PHP return an object JSON which may originate from a array using the function json_encode :

Example in assets/php/advantage-club.php:

<?php

   $dados = array( 'nome' => 'Willian', 'telefone' => '99 99999-9999' );
   exit(json_encode($dados) );

?>

In his job javascript:

<script>
    $.ajax({

        url: 'assets/php/advantage-club.php',
        type: 'POST',
        dataType: 'JSON',
        data: {
            "pass": "3d1fa6s0df51as8das6d2f1as036f15as8df90"
        },
        success: function(obj){
            console.log(obj.nome); // Saída será: Willian
            console.log(obj.telefone); // saída será : 99 99999-9999
        },
        error: function(err){
            console.log(err.status); //saída será 500, 404, 403... códigos de erro http
        }

    });
</script>

Browser other questions tagged

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