views:

312

answers:

4

I want to call a PHP file but want to pass an argument to the PHP file. Not getting the correct approach, I am attempting to write a cookie and read that cookie when the PHP file loads. But this is also not working. I am using following code to write and read cookie. I just want to test the read cookie function of JavaScript here. I know how to read the cookie value in PHP.

<script>
    function SetRowInCookie(NewCookieValue)
    {
     try
     {
      alert(NewCookieValue);
      document.cookie = 'row_id=' + NewCookieValue;
      loadCookies();   
     }
     catch(err)
     {
      alert(err.description);
     }
    }

    function loadCookies() {
    var cr = []; if (document.cookie != '') {
    var ck = document.cookie.split('; ');
    for (var i=ck.length - 1; i>= 0; i--) {
      var cv = ck.split('=');
      cr[ck[0]]=ck[1];
    }
    }
     alert(cr['row_id']);
    } 
</script>
+3  A: 

I'm not sure what in your code (running on the client's PC) you expect to cause the php script (running on the server) to run. You'll need to invoke the php by making some kind of http request (like get http://yoururl/recheckcookie.php). With at HTTP request, the javascript code on the client to queries the webserver for the output of your recheckcookie.php script. This script can then recheck the cookie, and return some/no output.

Look up XMLHttpRequest or preferably the corresponding JQuery to see how to perform the HTTP request.

Doug T.
+1  A: 

Well I'm not sure what it is you are ultimately trying to achieve but it sounds like using AJAX could be your solution. There is a good tutorial here.

AJAX will basically allow you to call a php script, pass it variables and then use it's output on your webpage.

RMcLeod
+2  A: 

Cookies are not the way to transfer variables between client and server. you should append key/variables pairs to your request URL using either a get (querystring) or post method.

jQuery ajax example;

$.get('http://www.myphpserver.com/script.php?row_id=' + NewCookieValue);
Matt Smith
Good idea, but jQuery is not included at the tags above ;)
daemonfire300
+2  A: 

I think, you dont need cookies. try it with $.post, where you can define which url will be called, something like:

$.post(url, params, callback_function);
cupakob