Use value returned via ajax with switch case on the current page

1

I'm basically trying to use value from a select returned via ajax with switch case. This switch case must be on the same send form page using the select value for a specific case.

My script perfectly returns the value of select via ajax. The only problem is that I can not use this value in the switch case on the current page because the value of $ _ POST ["aaa"] is not recognized. >

  

I've tried to redirect to the same page using url: this.action in ajax but I did not succeed.

Here's a step-by-step step-by-step guide that I need, and then the script.

  • I get the value of select with onChange
  • Displays a hidden div (displays main form)
  • The value is sent to return.php (server)
  • I get the value and use it in the switch case on the current page
  • With the case switch, custom fields are included for the main form according to what was chosen in the select.
  • index.php

    <div class="container">
    <form method ="" id="formStart" class="formStart" enctype="multipart/form-data">            
    <h2 style='color:blue'>Escolha o tipo de anúncio:</h2>          
        <select name="aaa" id="valorSel" >
            <option value="-1">Selecionar...</option>           
            <option value="1">Imóveis</option>
            <option value="2">Veículos</option>     
            <option value="3">Produtos</option>
        </select>
        <!-- <input type="Submit" name="submit" value="Next step" /> -->
        <br><br>
    </form>
    <br>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>$("#formStart").change(function(event){
            $("#formHide").show();  // exibir o form principal (oculto)
            event.preventDefault();
            $.ajax({
                data: $(this).serialize(),
                url: "retorno.php",
                type: "POST",
                dataType: "html",
                success: function(data){
                    $("#resultado").html(data);
                },
                error: function(){
                    alert("Problema ao carregar a solicitação via Ajax.");
                }
            });
        });
    </script>
    
    <div id="resultado"></div>
    
    <div id="formHide"  style="display:none;"> 
        <form action="<?php echo esc_url( $action ); ?>" method="post" id="submit-form" class="submit-form" enctype="multipart/form-data">          
            <?php 
            // Usar o valor do select retornado via ajax pela página "retorno.php" como switch case 
            switch ($_POST["aaa"]) {
                case 1:
                    echo "Imóveis";   // Para testes adicionei um echo e comentei os includes por enquanto.
                    //include "imoveis.php";
                    break;
                case 2:
                    echo "Veículos";
                    //include "veiculos.php";
                    break;
                case 3:
                    echo "Produtos";
                    //include "produtos.php";
                    break;
                case -1:
                    echo "Por favor escolha uma opção.";
                    break;
                default:
                    echo "Nada foi selecionado ainda. Por favor escolha uma opção.";
                    break;
            }       
            ?>
        </form>
    </div>  
    

    return.php

    <?php 
    
    if (isset($_POST['aaa'])) {
        echo $_POST['aaa'];
    } else {
        echo "Não retornou nenhum valor com ajax.";
    }
    

    Thanks in advance for your attention!

        
    asked by anonymous 01.01.2019 / 17:41

    3 answers

    1

    Given the specification quoted in the question, I thought of the following solution:

      

    This switch case needs to be on the same submit form page using the select value for a specific case.

    I called the file index.php in ajax , and in that second moment the POST["aaa"] will exist and will access the second part of the if drive. This second part of If will cause the PHP file to be called according to swich .

    Index.php

        <?php if (empty($_POST["aaa"])) { ?>
    
    <div class="container">
    <form method ="" id="formStart" class="formStart" enctype="multipart/form-data">            
    <h2 style='color:blue'>Escolha o tipo de anúncio:</h2>          
        <select name="aaa" id="valorSel" >
            <option value="-1">Selecionar...</option>           
            <option value="1">Imóveis</option>
            <option value="2">Veículos</option>     
            <option value="3">Produtos</option>
        </select>
        <!-- <input type="Submit" name="submit" value="Next step" /> -->
        <br><br>
    </form>
    <br>
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><script>$("#formStart").change(function(event){
            // exibir o form oculto
            event.preventDefault();
            $.ajax({
                data: $(this).serialize(),
                url: this.action,
                type: "POST",
                dataType: "html",
                success: function(data){
                    $("#formPrincipal").html(data);
                },
                error: function(){
                    alert("Problema ao carregar a solicitação via Ajax.");
                }
            });
        });
    </script>
    
    <div id="formPrincipal">
    <?php } else { ?>
    <form action="" method="post" id="submit-form" class="submit-form" enctype="multipart/form-data">
        <?php
        switch ($_POST["aaa"]) {
            case 1:
                include "imoveis.php";
                break;
            case 2:
                include "veiculos.php";
                break;
            case 3:
                include "produtos.php";
                break;
            case -1:
                echo "Por favor escolha uma opção.";
                break;
            default:
                echo "Nada foi selecionado ainda. Por favor escolha uma opção.";
                break;
        }              
        ?>
    </form>
    <?php } ?>
    </div>
    
        
    01.01.2019 / 19:36
    1

    I formulated this response exclusively with the project objective in mind:

      
  • I get the value of select with onChange
  •   
  • Displays a hidden div (displays main form)
  •   
  • The value is sent to return.php (server)
  •   
  • I get the value and use it in the switch case on the current page
  •   
  • With the case switch, custom fields are included for the main form according to what was chosen in the select.
  •   

    As mentioned in the comment, the logic of the project is wrong. The correct one would look like this:

  • Get the value of select via event change ;
  • Start a request via ajax to return the desired form;

    • Get the value passed via ajax;
    • Throws that value into switch ;
    • Returns (displays) the desired form file (where the fields are supposed to be);
  • Show hidden% with the form returned via ajax ;

  • Finished the theory, let's go to the codes:

    index.php :

    <!DOCTYPE html>
    <html>
        <head>
            <title>Formulário dinâmico por LipESprY</title>
            <!-- <script type="text/javascript" src="prereq/jquery-3.3.1.min.js"></script> -->
            <script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script></head><body><h2style='color:blue;'>Escolhaotipodeanúncio:</h2><selectname="aaa" id="valorSel" size="1">
                <option value="0" disabled="disabled" selected="selected">Selecione:</option>
                <option value="1">Imóveis</option>
                <option value="2">Veículos</option>
                <option value="3">Produtos</option>
            </select>
    
            <div id="formHide"  style="display:none;">
                <form action="trata_formulario.php" method="post" id="submit-form" class="submit-form" enctype="multipart/form-data">
                    <div id="form-resultado"></div>
                </form>
            </div>
    
        </body>
    
        <script>
            //$("#valorSel").change(function(event){
            $("#valorSel").on('change', function(event){
    
                $("#formHide").show();  // exibir o form principal (oculto)
                // event.preventDefault(); // Não tem necessidade, já que vai pegar o evento 'change'
                $.ajax({
                    url: "retorno.php",
                    data: {
                        aaa: $('#valorSel').val()
                    },
                    type: "post",
                    dataType: "html"
                })
                .done(function(data){
                    $("#form-resultado").html(data);
                })
                .fail(function(erro){
                    console.log(erro);
                    alert('Problema ao carregar o formulário via ajax');
                });
    
            });
        </script>
    
    </html>
    

    Notice that I'm using jQuery 3.3.1 , which has some differences in sintaxe of ajax ;

    return.php :

    <?php
    if (!empty($_POST['aaa'])) {
        switch ($_POST['aaa']) {
            case 1:
                include 'forms/imoveis.php';
                break;
            case 2:
                include 'forms/veiculos.php';
                break;
            case 3:
                include 'forms/produtos.php';
                break;
            default:
                die(
                    'Nada foi selecionado ainda. Por favor escolha uma opção.'
                );
        }
    } else
        die(
            'Requisição inválida. Esta página pertence ao tratamento de um formulário e espera um parâmetro.'
        );
    

    Repair the files of each form should be in the div folder (only for organization reasons).

    I wrote a project based on my answer. It's a bit more complete than this answer, but since it's not the goal to create / fix the other files, I did not even want to post them here. If you want, you can check it out at my GitHub / LipESprY / sopt-use-value-returned-via-ajax-with-switch-case-on-current-page .

    Another question: I have reformulated much of your code, as I had already combined in the comment. Explaining every change I made would generate an immense rather unnecessary reading. If you want to see the detailed changes, just look at this commit on GitHub .

        
    01.01.2019 / 22:13
    0

    I have not seen a need for ajax in this code since the form below works well.

    functional example

    <div class="container">
    <form method ="post" id="formStart" class="formStart" enctype="multipart/form-data">            
    <h2 style='color:blue'>Escolha o tipo de anúncio:</h2>          
        <select name="aaa" onchange="this.form.submit()">
            <option value="-1">Selecionar...</option>           
            <option value="1">Imóveis</option>
            <option value="2">Veículos</option>     
            <option value="3">Produtos</option>
        </select>
    </form>
    <br>
    
     <?php if (!empty($_POST["aaa"])) { ?>
    
    <div id="formPrincipal">
        <form action="" method="post" id="submit-form" class="submit-form" enctype="multipart/form-data">          
            <?php 
            // Usar o valor do select retornado via ajax pela página "retorno.php" como switch case 
            switch ($_POST["aaa"]) {
                case 1:
                    echo "Imóveis";   // Para testes adicionei um echo e comentei os includes por enquanto.
                    //include "imoveis.php";
                    break;
                case 2:
                    echo "Veículos";
                    //include "veiculos.php";
                    break;
                case 3:
                    echo "Produtos";
                    //include "produtos.php";
                    break;
                case -1:
                    echo "Por favor escolha uma opção.";
                    break;
                default:
                    echo "Nada foi selecionado ainda. Por favor escolha uma opção.";
                    break;
            }       
            ?>
        </form>
    <?php } ?>
    </div>
    
        
    02.01.2019 / 17:49