Use value returned via ajax with switch case on current page

Asked

Viewed 367 times

1

Basically I’m trying to use value of a select returned via ajax with switch case. This switch case needs to be on the same form submission page using the select value for a specific case.

My script returns the value of select perfectly via ajax. The only problem is that i can’t use this value in the switch case on the current page, for the value of $_POST["aaa"] is not recognized.

I have tried redirecting to the same page using url: this.action in ajax but did not succeed.

Follow below in detail step by step what I need and then the script.

  1. I take the value of select with onChange
  2. Displays a hidden div (displays the main form)
  3. The value is sent to return.php (server)
  4. I take the value and use the switch case on the current page
  5. With the switch case custom fields are included for the main form according to what was chosen in 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>  

php return.

<?php 

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

From now on I thank you for your attention!

  • Friend, logic is not cool. If you are going to make an ajax request, why don’t you return the fields you need? For you to return PHP value and deal with Javascript, it would be better to use JSON. But in your case, there is no need. You can "create" your fields directly with ajax, as you said... If you are interested, I can formulate an answer. Of course you’ll have to redo at least half your code...

  • Lipespry, I would prefer to handle everything with php, but without ajax I would have to use the Submit button and the refresh page which is not what I need. I tried to do with javascript, but in the call of includes gave error. However your idea is welcome and maybe above my need. Feel free and look forward to your fluffy. Hug.

  • Still I see no need for ajax, I made a small modification in my reply to meet that remark of yours. Before you go sticking ajax in everything, at least think before. Was it necessary ? really improved user experience ? Or I just found the technology cool, and I decided to swell the load of my application or site, with several lines of javascript code to do something simple?

3 answers

1


I meet the specification mentioned in the question, I thought of the following solution:

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

I called the file itself index.php in the ajax, and in that second moment the POST["aaa"] will exist and will access the second part of driving if. That second part of If will cause it to be called the PHP file according to the 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>
  • In $("#formHide").html(data); should not point to the target form: submit-form?

  • Almerindo Abreu congratulations! I made only a small change putting the switch inside the form and worked perfectly. You were able to see the solution from another angle by inserting the condition that made all the difference. I keep wondering why I hadn’t thought of it before kkkk. Thank you so much for your contribution. Thanks a lot!!!

  • And what is the use of this ajax?

  • Without the ajax when returning the value, the select field disappears. Already with ajax the select field remains, giving the opportunity for the user to change his choice . Hug

1

I formulated this answer exclusively thinking about the goal of the project:

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

As mentioned in the comment, the logic of the project is wrong. The correct would be so:

  1. Take the value of select via event change;
  2. Start a request via ajax return the desired form;

    • Take the value passed via ajax;
    • Plays such value on switch;
    • Returns (displays) the desired form file (supposedly where the fields would be);
  3. Display a div hidden with the form returned via ajax;

Finalized 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>

        <h2 style='color:blue;'>Escolha o tipo de anúncio:</h2>
        <select name="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 I’m using the jQuery 3.3.1, that has some differences in syntax of ajax;

php return.:

<?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.'
    );

Note the files of each form must be in the folder forms/ (only for organisational reasons).

I designed a project based on this answer. It is a little more complete than this answer, but as it is not the goal to create/fix the other files, nor did I make a point to post them here. If you want, you can check my Github/Lipespry/sopt-use-value-returned-via-ajax-com-switch-case-on-current page.

Another issue: I reworked much of your code, as I had already agreed in the commentary. Explaining every change I made would generate an immense reading somewhat unnecessary. If you want to see the detailed changes, just look at this commit on Github.

  • Lipespry! Thanks for the help, however it’s like I said: I needed swith on the index.php page and not on the return.php page, because my biggest problem was being able to use the value of select on the index.php page itself without refresh. On the return.php page I had already done and succeeded before. Thanks in a way for the strength.

  • @skyline Have you at least had the effort to run my code? I understand you’ve already solved it, but I don’t know. I’m not comfortable with you using this one switch in the same file this way. When you realize, your code will be a beautiful mess. Everything mixed... But do what, right?! Important is you understand your code...

  • @ Lipespry Yes! Your code works perfectly and I had already achieved this way before. My main goal was to use the value of the select passed to the Switch on the index.php page.

  • @skyline Se resolveu the problem, valendo! ;)

0

I saw no need for ajax in your code since the form below works well.

<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>
  • without ajax (the way you mencinou), when returning the value the field select some. Already with ajax the select field remains, giving the opportunity for the user to still change his choice. Hug

  • Still I see no need for ajax, I made a small modification in my reply to meet that remark of yours. Before you go sticking ajax in everything, at least think before. Was it necessary ? really improved user experience ? Or I just found the technology cool, and I decided to swell the load of my application or site, with several lines of javascript code to do something simple?

  • That page retorno.php does not make sense just to take the value via post and return it the way it was received. It would make more sense to do a processing with the value sent by the form and return another value, for example, a verification of a value in a database or an Internet, or update or etc....

  • Leo. Its code is functional, but with ajax the return is more presentable and less crude, and may even include a fade. Already the Submit() inserted in the event forces a reloud on the page. Another thing, with ajax after choosing the option, keeps the last active choice in select and without ajax it goes back to the "select" option in select. But that’s the least of it. The problem is that now I’m trying to insert this code in my wordpress theme and does not work at all, already outside wordpress works beauty. I don’t know what else to do.

Browser other questions tagged

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