Convert php code to reply to ajax

-1

Here I am again with my silly questions but that give me the biggest headache .. Come on, I have a script that takes the data that the user typed and sends it to the server, it works perfectly, however I wanted to pass it through ajax for several reasons but I could not because I never worked with ajax and now I need to be in the hand .. If someone can help me to convert this script so that it provides a response to an ajax request I thank you .. Good evening! / p>

The code .. (obs: this variable generates like I had not yet finished, it would pick up on the table like the amount of like that post it received and it would identify the post by its id ...) p>

        <?php

        $status = 1;

        if( isset( $_POST['publicar'] ) ){

            date_default_timezone_set('America/Sao_Paulo');
            $form['data']       = date('Y-m-d H:i:s');
            $form['conteudo']   = str_replace( '\r\n', "\n", DBEscape( trim( $_POST['conteudo'] ) ));
            $form['status']     = DBEscape( strip_tags( trim( $status ) ) );
            if( empty( $form['conteudo'] ) )
                echo'';
            else {

                $dbCheck = DBRead( 'posts', "WHERE conteudo = '". $form['conteudo'] ."'" );

                if( $dbCheck )
                    echo '<script>alert("Desculpe, mas já contaram esse segredo!");</script>';
                else {

                    if( DBCreate( 'posts', $form ) ){

                        // Vai procurar no DB o post e em seguida pegar seu id para criar uma
                        // tupla na tabela de likes
                        $IdCheck = DBRead( 'posts', "WHERE conteudo = '". $form['conteudo'] ."'", 'id');    
                        $UserIdCheck = DBRead( 'usuarios', "WHERE email = '". $_SESSION['email'] ."'", 'id');   
                        $id = (string)$IdCheck[0]['id'];
                        //echo $id."</br>";
                        $user = (string)$UserIdCheck[0]['id'];
                        //echo $user;
                        $like = array(
                                'id_post'=> $id,
                                'n_like' => 0,
                                'id_user'=> $user
                            );
                        $geralike = DBCreate('likes', $like);
                        if($geralike)
                            echo '<script>console.log("Likes ativos do post "'.$form['conteudo'].');</script>';
                        else
                            echo '<script>console.log("Acho que ia mas num foi ¯\_(ツ)_/¯");</script>';


                        // este pedaço abaixo foi uma fraca tentativa de retornar para o feed o post recem feito, bom eu não tinha terminado ent ficou pela metade.
                        //Resposta apost concluir o post

                        //$lastpost = DBRead( 'posts', "WHERE id = '". $id ."'", 'conteudo');
                        //$postcont = (string)$lastpost[0]['conteudo'];
                        //$post = post($postcont);
                        //echo "<script>$('div.overview').append(".$post.");</script>";
                        //echo '<script>document.getElementById("myP").style.visibility = "visible";</script>';
                        //echo '<script>location.reload();</script>';
                    }
                    else
                        echo '<script>alert("Desculpe, ocorreu um erro...");</script>';
                }
            }

        }
?>

Obs2: It checks if there is an equal post comparing the content since there is no title.

    
asked by anonymous 09.07.2016 / 10:35

2 answers

2

I can not simply 'convert' the code to accept ajax request because I do not have all the code. But I'll cite a simpler example of a form sending data by ajax and taking that data in a script php .

index.php file :

<?php
session_start();
/* destruir sessão
foreach ($_SESSION as $key => $value)
    unset($_SESSION[$key]);
session_destroy();
*/
$_SESSION['token'] = crypt("MyAppIDKey" . time() . "MyTokenSecurity");
?>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Segurança Ajax</title>
        <script  src="jquery.min.js"></script>
    </head>

    <body>
        <form class="myForm" method="post">
            <p>
                <label>Nome: </label>
                <input type="text" name="nome" />
            </p>

            <p>
                <label>Idade: </label>
                <input type="number" name="idade" />
            </p>

            <p>
                <label>E-mail: </label>
                <input type="email" name="email" />
            </p>

            <p>
                <input type="hidden" name="token" value="<?php echo $_SESSION['token']; ?>" />
                <input type="submit" value="Enviar" />
                <input type="reset" value="Limpar" />
            </p>
        </form>

        <div class="result"></div>
        <table class="myTable">
            <thead>
                <tr>
                    <th>Nome</th>
                    <th>Idade</th>
                    <th>Email</th>
                </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
        <script>
        $(function()
        {
            $(".myTable").hide();
            $("form.myForm").submit(function(e)
            {
                $.ajax(
                {
                    type: "POST",
                    url: "myScript.php",
                    data: 
                    {
                        nome: $("input[name = nome]").val(),
                        idade: $("input[name = idade]").val(),
                        email: $("input[name = email]").val(),
                        token: $("input[name = token]").val()
                    },
                    success: function(result)
                    {
                        if(result.indexOf("sucesso") >= 0)
                        {
                            $(".myTable").show('fast');
                            $(".myTable tbody").html(result.replace("sucesso", ""));
                            alert("Pessoa cadastrada!");
                        }   
                        else
                        {
                            alert("Erro: " + result);
                        }
                    }
                });
                e.preventDefault();
            });
        });
        </script>
    </body>

</html>

File myScript.php :

<?php
session_start();
if(isset($_POST['token']) and $_POST['token'] === $_SESSION['token']):
    if(!empty($_POST['nome'])):
        if(is_numeric($_POST['idade'])):
            if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ):
                if(!isset($_SESSION['table'])):
                    $_SESSION['table'] = "";
                endif;

                $_SESSION['table'] .=   "<tr><td>{$_POST['nome']}</td>" . 
                                        "<td>{$_POST['idade']}</td>" .
                                        "<td>{$_POST['email']}</td></tr>";

                echo "sucesso" . $_SESSION['table'];
            else:
                echo "Email inválido";
            endif;
        else:
            echo "Idade é inválida";
        endif;
    else:
        echo "Nome é obrigatório";
    endif;
else:
    echo "Token inválido";
endif;

It's not very nice to return data in HTML to ajax , but to take less time I used it like this. Also I put a security token to prevent insertion attacks.

Another ideal is to use a layered architecture to keep the code more standardized, following a question that I make the same example in MVC (without deactivating the refresh page with e.preventDefault() ):

Protecting an ajax request ?

EDIT: I had more time so I decided to turn the return into json :

The ajax would look like this:

$.ajax(
{
    type: "POST",
    url: "myScript.php",
    dataType: "json",
    data: 
    {
        nome: $("input[name = nome]").val(),
        idade: $("input[name = idade]").val(),
        email: $("input[name = email]").val(),
        token: $("input[name = token]").val()
    },
    success: function(result)
    {
        if(result.retorno == "sucesso")
        {
            $(".myTable").show('fast');
            var string = "";

            $.each(result.nomes, function(key, value)
            {
                string +=   "<tr>" +
                                "<td>" + value + "</td>" +
                                "<td>" + result.idades[key] + "</td>" +
                                "<td>" + result.emails[key] + "</td>" +
                            "</tr>";
            });


            $(".myTable tbody").html(string);
            alert("Pessoa cadastrada!");
        }   
        else
        {
            alert("Erro: " + result.retorno);
        }
    }
});

And the snippet in PHP , would look like this (when the email was validated):

if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) ):
    if(!isset($_SESSION['nomes'])):
        $_SESSION['nomes'] = array();
        $_SESSION['idades'] = array();
        $_SESSION['emails'] = array();
    endif;

    array_push($_SESSION['nomes'], $_POST['nome']);
    array_push($_SESSION['idades'], $_POST['idade']);
    array_push($_SESSION['emails'], $_POST['email']);

    echo json_encode(array
                    (
                    'retorno' => 'sucesso',
                    'nomes' => $_SESSION['nomes'],
                    'idades' => $_SESSION['idades'],
                    'emails' => $_SESSION['emails']
                    ));
else:
    echo json_encode(array('retorno' => 'Email inválido'));
endif;
    
09.07.2016 / 16:44
3

A PHP page called via Ajax or via "normal" has the same code. What you can tell is the return format. In your case, you are printing a string with JavaScript code (which is not correct in any way).

The best way to return a data to Ajax requests is a JSON . PHP has the json_encode function that converts an Array to a string in JSON format.

Example of a change in your code:

From

echo '<script>alert("Desculpe, mas já contaram esse segredo!");</script>';

To

echo json_encode(array('msg' => 'Desculpe, mas já contaram esse segredo!'));

And on the client you trigger alert() with the message returned by the PHP page. Example of ajax call with jQuery:

$.ajax({
  method: "POST",
  url: "pagina.php",
  data: { publicar: "1", conteudo: "Teste" },
  dataType: "json"
})
.done(function( response ) {
  alert( response.msg );
});
    
09.07.2016 / 16:24