سؤال

Lets assume I have 2 cookie values set. I know that the syntax of cookie objects are quite often not very simple and can't just be set into variables easily. So I have used the following code to return 2 variables for the 2 cookies:

cookie_name = "username";
cookie_name2 = "password";

var YouWrote=getName();
var YouWrote2=getName2();

function getName() {
    if(document.cookie)
    {
    index = document.cookie.indexOf(cookie_name);
    if (index != -1)
    {
    namestart = (document.cookie.indexOf("=", index) + 1);
    nameend = document.cookie.indexOf(";", index);
    if (nameend == -1) {nameend = document.cookie.length;}
    YouWrote = document.cookie.substring(namestart, nameend);
    return YouWrote;
}}}

function getName2() {
    if(document.cookie)
    {
    index = document.cookie.indexOf(cookie_name2);
    if (index != -1)
    {

    namestart = (document.cookie.indexOf("=", index) + 1);
    nameend = document.cookie.indexOf(";", index);
    if (nameend == -1) {nameend = document.cookie.length;}
    YouWrote2 = document.cookie.substring(namestart, nameend);
    return YouWrote2;
}}}

Now YouWrote and YouWrote2 contains the cookie value (exact same as the one stored in the browser). Now I am wondering how I can use Javascript or Jquery to store the two YouWrote variables into JSON objects and send it via Post method.

I'm thinking something along the lines of:

$(document).ready(function () {
$.ajax
        ({
            type: "POST",
            url: "Insert URL Here",
            dataType: 'json',
            async: false,
            data: ??????????????????????????

});

Stuck at the data part. Not sure if this is the right way of doing it.

لا يوجد حل صحيح

نصائح أخرى

First of all I don't think that storing username and password client side in a cookie is a good idea. Instead you could use session token stored in cookie to verify if user is logged in. Secondly you can use one function to get value of cookie based on it's name. Writing one function i.e. getCookieVal( nameParameter ) could return proper value - saves time and is not so prone to error.

But, let's get to the point. You need to use json notation to pass js object do data, like this:

data : { you_wrote_1 : YouWrote , you_wrote_2: YouWrote2 } 

That's it. You can then grab these variables on the server using $_POST table - with php.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top