[PHP/JavaScript]: Call PHP file through JavaScript code with argument

294

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>
790

Answer

Solution:

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.

841

Answer

Solution:

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);
408

Answer

Solution:

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);
14

Answer

Solution:

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.

People are also looking for solutions to the problem: web services - php and webservices

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.