-1

I need to convert php code to javascript and display it on the html page. I'm setting my cookie (example with some special errors):

<?php

        setcookie("data","test1=avalue;test2=bvalue;test3=cvalue;test4=;==;=;=;",time()+(60)*(60));

?>

then another page is reading/checking errors:

<?php
if(isset($_COOKIE)){
    $data=array();
    if(strlen($_COOKIE['data'])>0){
        if((strstr($_COOKIE['data'],";")!=NULL)and(strstr($_COOKIE['data'],"=")!=NULL)){
            $c=explode(";",$_COOKIE['data']);
            foreach($c as $t){
                if(strstr($t,"=")!=NULL){
                    $v=explode("=",$t);
                    if($v[0]!=""){
                        if($v[1]!=""){
                            $data[$v[0]]=$v[1];
                            }else{
                                $data[$v[0]]="n/a";
                                }
                        }
                    }
                }
            }else{
                $data["errors"][]="corupted cookie data";
                }
        }else{
            $data["errors"][]="specific cookie not found";
            }
    }else{
        $data["errors"][]="cookies must be enabled";
        }
?>

and gived example is filtered all bugus data and im displaying it with print_r in php language:

Array (
    [test1] => avalue
    [test2] => bvalue
    [test3] => cvalue
    [test4] => n/a
)

So what i want, to get the reading code (writen in php in my example) get in pure javascript language. Note that i did special errors "=;==;=;=;" in the cookie, they must be proper filtered in javascript also like in my php code.

1 Answer 1

0
function func1(str) {
    var data = {};
    data["errors"] = [];
    if(str.length > 0){
        if(str.indexOf(';') != -1 && str.indexOf('=') != -1) {
            var ary = str.split(';');
            for(var i = 0, l = ary.length; i < l; i++) {
                if(/[^\=]+\=[^\=]*/.test(ary[i])){
                    var v = ary[i].split('=');
                    if(v[1] !== ''){
                        data[v[0]]=v[1];
                    }else{
                        data[v[0]]="n/a";
                    }
                } else {
                    data["errors"].push("corupted cookie data");
                }
            }
        } else {
            data["errors"].push("specific cookie not found");
        }
    } else {
        data["errors"].push("cookies must be enabled");     
    }
    console.log(data);
    return data;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.