Pass php session value to Ajax

Asked

Viewed 1,153 times

2

I need to take a value of a php session that is on a page where I have a contact form and go through Ajax to another page, on this page I make the check if the values are equal or not, but I am not able to realize.

My captcha code creates the view session:

<?php

session_start();

$codigoCaptcha = substr(md5( time()) ,0,9); 
$_SESSION['captcha'] = $codigoCaptcha;  

$imagemCaptcha = imagecreatefrompng("fundocaptch.png");
$fonteCaptcha = imageloadfont("anonymous.gdf");
$corCaptcha = imagecolorallocate($imagemCaptcha,127,82,53);

imagestring($imagemCaptcha,$fonteCaptcha,15,5,$codigoCaptcha,$corCaptcha);

header("Content-type: image/png");
imagepng($imagemCaptcha);
imagedestroy($imagemCaptcha);

?>

I tried to pass the session variable like this:

    <script>
jQuery(document).ready(function(){
    $("#submit").on("click", function(event){
        var nome      = $("#nome").val();
        var email     = $("#email").val();
        var uf        = $("#uf").val();
        var municipio = $("#municipio").val();
        var telefone  = $("#telefone").val();
        var grupo     = $("#grupo").val();
        var assunto   = $("#assunto").val();
        var mensagem  = $("#mensagem").val();   
        var captcha   = $("#captcha").val();
        var captcha_sessao = $("#SESSION['captcha']").val();    

        alert(captcha_sessao);

        var emailFilter = /^.+@.+\..{2,}$/;
        var illegalChars= /[\(\)\<\>\,\;\:\\\/\"\[\]]/;

        if((emailFilter.test(email))||email.match(illegalChars)){
            $.ajax({
                type: "POST",
                url: "processo.php",
                dataType: "json",
                beforeSend: function(){
                    $(".processo").html('Gravando contato...');
                },
                data: {'nome':nome,
                       'email':email,
                       'uf':uf,
                       'municipio':municipio,
                       'telefone':telefone,
                       'grupo':grupo,
                       'assunto':assunto,
                       'mensagem':mensagem,
                       'captcha':captcha,
                       'captcha_sessao':captcha_sessao},
                success: function(json){
                    if(json.tipo == "0"){ // erro
                        $(".processo").html("<span class='erro'>"+json.msg+"</span>");
                    }else{ // sucesso
                        $(".processo").html("<span class='sucesso'>"+json.msg+"</span>");
                        cleanFields();
                    }
                }
            });
        }else{
            $(".processo").html("<p style='color:#f25824'>Por favor, informe um e-mail válido.</p>");
        }
        event.preventDefault();
    });

}); 

</script>       

The value of this variable which is the field entered with the generated captcha is sent to the process page.php:

var captcha   = $("#captcha").val();

I don’t know exactly how to proceed.

1 answer

3


From what I understand of the question and the code, you’re looking to do a CAPTCHA check. When creating a server side session (with PHP), usually a cookie on the client side is created to store that session ID.

So: Your script saves captcha in session:

$_SESSION['captcha'] = $codigoCaptcha;

All you need to do is submit the form request via AJAX, with the value of the field the user typed:

var captcha   = $("#captcha").val();

That is, you do not need to pass on other information relating to sessions or CAPTCHA. What happens now is the following: On the server side, with PHP, you access the session again, and check if the value saved by the CAPTCHA generator script is the same that the user typed in the field. Example:

php process.

<?php
session_start();

if($_POST['captcha'] != $_SESSION['captcha'])
    die('O captcha digitado é inválido');

The session and its values are created by PHP, and are saved on the server. I suggest a look at the session documentation here and here.

  • Hello @Calebe Oliveira, thanks for the tips, I solved my problem, I cleaned up the history and it worked.

Browser other questions tagged

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