开发者

Why does this javascript variable not get set into a cookie in php?

I have the javascript function below which sends the variable 'widgets' to a php file via an ajax call. If I then send the variable widgets back to the html document and echo it out it displays on the clientside screen correctly. BUT when it is sent to php I try to set it into a cookie and the cookie doesn't get set. Here is the javascript function:

function positions(){
    var widgets = '';
    var col = document.getElementById('col');
    for(i = 0; i < col.childNodes.length; i++) {
        var str1 = col.childNodes[i].className;
        if(str1 && str1.match('widget')) widgets+='&c[1]['+i+']='+col.childNodes[i].id;
    }

xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xmlhttp.open('POST', '/ajaxwidgetpositions开发者_如何学Python.php', true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("widgetpositions="+widgets);
var e = document.getElementById('widget_data');
e.innerHTML += '<p><a>' +widgets + '</a></p>';
xmlhttp.send(null);
return true;
}

And here is the php:

<?php
$widgetpositions = $_POST["widgetpositions"];
setcookie("widgetss", $widgetpositions);
?> 

For what it's worth, the javascript varibale 'widgets' has the form:

&c[1][1]=widget_5&c[1][2]=widget_11&c[1][4]=widget_1&c[1][6]=widget_13
&c[2][2]=widget_6&c[2][4]=widget_10&c[2][6]=widget_2&c[2][8]=widget_3
&c[3][3]=widget_7&c[3][5]=widget_12&c[3][7]=widget_8

I cut out some of the function positions code to make it more readable so 'widgets'above is a bit longer than you might expect, but that is the form it takes. Maybe that is too much to store in a cookie?

Does anyone know why it's not getting set to a cookie? Please help.


Are you sure that the data is posted an recived on the PHP side? Check this with var_dump($_POST).

If it is, are you sure your session doesn't expire or something? Since you don't have an expiration time when you set your cookie it will get wiped when the session dies.

Try with

<?php
$widgetpositions = $_POST["widgetpositions"];
setcookie("widgetss", $widgetpositions, time()+60*60);
?>

Does the cookie still not set?


this is how i set and delete cookies without having problem in IE

  //Always use domain and path to control your cookies better.
  //otherwise in IE you can have problem.

  //setcookie
  $domain = "domain.com"; //without subdomain.
  $domain = "/path_of_this_file/"; //without subdomain.

  $widgetpositions = $_POST["widgetpositions"]; 
  setcookie("widgetss", $widgetpositions, time()+3600, $path, $domain, false); 

  //delete cookie
  setcookie("widgetss", '', time()-31536001, $path, $domain, false); 

?>  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜