Convert php code to reply ajax

Asked

Viewed 526 times

0

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

Just follow the code. (Obs: this variable generates like I hadn’t finished yet, it would pick up on the like table the amount of like q that post received and it would identify the post by its id... )

        <?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>';
                }
            }

        }
?>

Note 2: It checks if there is already an equal post comparing the content because there is no title.

2 answers

3

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

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

Example of a change in your code:

Of

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

To

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

And in the customer you fire the alert() with the message returned by the PHP page. Example of calling Ajax with jQuery:

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

3


I cannot simply 'convert' the code to accept request ajax, because I don’t have all the code. But I will quote a simpler example of a form sending data by the ajax and taking this data in a script php.

Filing cabinet index php.:

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

Filing cabinet 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 get back data in HTML to the ajax, but to take less time I used so. I also put a token security to prevent insertion attacks.

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

How to protect an ajax request?

EDIT: I had more time so I decided to turn the return in 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 passage in PHP, would look like this (when validated email):

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;

Browser other questions tagged

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