简体   繁体   中英

JavaScript value to PHP variable

JavaScript code:

<script type="text/javascript">
$("#test").click(function() {
  getQuerystring(this);
  return false;
});

function getQuerystring(el) {
  console.log(el.href);
  var getUrlParameter = function(sParam) {
    var sPageURL = el.href.split('?')[1],
      sURLVariables = sPageURL.split('&'),
      sParameterName;

    for (var i = 0; i < sURLVariables.length; i++) {
      sParameterName = sURLVariables[i].split('=');

      if (sParameterName[0] === sParam) {
        return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
      }
    }
  };

  var blog = getUrlParameter('c');
  //document.getElementById('detail').innerHTML = blog;
  document.cookie = "blog = " + blog;
}
</script>

html code

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="border: dashed; size: auto;">
  <a name="divtest" href="#detail?c=active" id="test">testing</a>
</div>
<div id="detail" style="border: 2px; size: auto;">
    <?php
    $chk = $_COOKIE['blog'];
    echo $chk;
    ?>
</div>

The JavaScript code should set the cookie, and then php get the values saved in the cookie. I basically want to send value from JavaScript to php on the same page. but it seems to be an error "Notice: Undefined index: blog in C:\wamp64\www\test\ajax.php on line 40". I have searched a lot but didn't find the proper solution. How can I correct my code?

Jquery ajax:

$.ajax({
    url: "path_to_ajax_file",
    type: "post",
    success: function (response) {
            document.getElementById(“result”);
    }
 });

HTML code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="border: dashed; size: auto;">
<a name="divtest" href="#detail?c=active"  id="test">testing</a>
</div>
<div id="detail" style="border: 2px; size: auto;">
  <span id=“result”></span>
</div>

Ajax code:

echo $_COOKIES[“blog”];

So first create HTML structure then call ajax in javascript by jquery and last create ajax file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM