Send a Value from HTML Link to Server Without Page Refresh

p-plater
p-plater used Ask the Experts™
on
Hello

I have a Link / Button on a HTML Web page and when it is Clicked I need to change a PHP $_SESSION Value on the Server Without the Page Refreshing.
I don't care what Language I use.

Thanks
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Dave BaldwinFixer of Problems
Most Valuable Expert 2014

Commented:
AJAX can be used for that.  A javascript function in the page code can make a page request to a PHP page that changes the value for you.  I don't really have a demo at the moment that I can post for you.  All of mine have other weird code in them.
Dave BaldwinFixer of Problems
Most Valuable Expert 2014
Commented:
Here http://www.w3schools.com/ajax/default.asp is the W3Schools pages about AJAX.
Most Valuable Expert 2011
Top Expert 2016
Commented:
Many professionals like jQuery for this sort of thing.
http://jquery.com/

Please be aware that any data you send to a server-side script from the client machine is an attack vector.  Do not rely on the contents unless you have filtered it on the server, after receiving the client request.

The code snippet contains an old piece that I believe came from Rasmus Lerdorf of PHP fame.  It shows some of the moving parts of AJAX communication.  Take note of line 26 and line 67.  This example uses the GET method to send the request to the background script.  The GET method has the advantage that you can test the background script easily, by just typing the URL arguments into the address bar of a browser.  In the case of this script you would test it with a URL that said ajaxprocessor.php?action=foo.

However your requirement is to change the contents of the session, and under the laws of HTTP that means that you must use a POST request.  My suggestion is to start your background coding by using a GET request until the process works the way you want, then switch the code to use the POST request.

Best regards, ~Ray
I find a lot of this AJAX stuff a bit of a hype.  Lots of people have
been using similar things long before it became "AJAX".  And it really
isn't as complicated as a lot of people make it out to be.  Here is a
simple example from one of my apps.  

/* THE JAVASCRIPT TO CREATE THE AJAX INFRASTRUCTURE */
/* FUNCTION TO CREATE THE BROWSER-DEPENDENT REQUEST OBJECT */
function createRequestObject() 
{
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer")
    {
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else
    {
        ro = new XMLHttpRequest();
    }
    return ro;
}


/* FUNCTION TO SEND THE REQUEST */
function sendReq(action) 
{
    http.open('get', 'ajaxprocessor.php?action='+action);
    http.onreadystatechange = handleResponse;
    http.send(null);
}


/* FUNCTION TO HANDLE THE RESPONSE */
function handleResponse()
{
    if(http.readyState == 4)
    {
        var response = http.responseText;
        var update = new Array();

        if(response.indexOf('|' != -1))
        {
            update = response.split('|');
            document.getElementById(update[0]).innerHTML = update[1];
        }
    }
}


/* CREATE THE OBJECT */
var http = createRequestObject();

/* END OF THE JAVASCRIPT */

This creates a request object along with a send request and handle
response function.  So to actually use it, you could include this js in
your page.  Then to make one of these backend requests you would tie it
to something.  Like an onclick event or a straight href like this:

<a href="javascript:sendReq('foo')">[Foo]</a>

That means that when someone clicks on that link what actually happens
is that a backend request to ajaxprocessor.php?action=foo will be sent.

In ajaxprocessor.php you might have something like this:

/* THE PHP TO HANDLE THE REQUEST FROM THE FRONT-END SCRIPT */
switch($_GET['action']) 
{
    case 'foo':
      // DO WHATEVER PROCESSING IS APPROPRIATE
      // THEN RETURN A RESPONSE STRING TO handleResponse()
      echo "foo|Foo done";
      break;
      // ETC...
}

Now, look at handleResponse.  It parses the "foo|Foo done" string and
splits it on the '|' and uses whatever is before the '|' as the dom
element id in your page and the part after as the new innerHTML of that
element.  That means if you have a div tag like this in your page:

<div id="foo">Waiting for Foo</div>

Once you click on that link, that will dynamically be changed to:

<div id="foo">Foo done</div>

That's all there is to it.  Everything else is just building on top of
this.  Replacing my simple response "id|text" syntax with a richer XML
format and making the request much more complicated as well.  Before you
blindly install large "AJAX" libraries, have a go at rolling your own
functionality so you know exactly how it works and you only make it as
complicated as you need.  Often you do not need much more than what I
have shown here.

Expanding this approach a bit to send multiple parameters in the
request, for example, would be really simple.  Something like:

function sendReqArg(action,arg) 
{
    http.open('get', 'ajaxprocessor.php?action='+action+'&arg='+arg);
    http.onreadystatechange = handleResponse;
    http.send(null);
}

And your handleResponse can easily be expanded to do more interesting 
things than just replacing the contents of a div.

-Rasmus (Lerdorf?)

Open in new window

CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

Top Expert 2007

Commented:
I take exception to some of your function createRequestObject() - it is archaic. A better example is:
//
function createRequestObject() {
    
    // If the result of invoking this function is NULL, then something is terribly wrong...
    var xhr = null;
    
    if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+...
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // Older IE
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xhr;
}
//

Open in new window

Most Valuable Expert 2011
Top Expert 2016

Commented:
@Badotz, It's not actually my function -- it's an old piece of demonstration code from Rasmus.  I like your example better.  Either way, the AJAX principles are about the same.
Top Expert 2007

Commented:
Ah, sorry.

I also prefer the "POST" method over the "GET" method because the data is plainly visible, and the 1,024-character limit could be an issue...
Dave BaldwinFixer of Problems
Most Valuable Expert 2014

Commented:
But @Badotz, if his AJAX routine is just to notify a PHP page to change a variable in the background, there is nothing to POST.  And in the background, there is nothing to see.
Top Expert 2007

Commented:
Perhaps.

In my case, I only use POST. I don't mind the extra bit of overhead involved, and I don't have to remember which method to use. I create two JSON objects: one to control the invocation and the other to instruct the server and hold the passed parameters (if any).
Commented:
Let me suppose the code for the html button is :

<button id="my_button" value="Button">Button</button>

and the link is

<a href="page.php" id="my_link"></a>
have a php file change_session.php to change the value of the variable $_SESSION['my_session'] .

then a dd this javascript code within the head section:



<script type="text/javascript">

$(document).ready(function(){


$("#my_link").click(function(){


$.post("change_session.php");

});



$("#my_button").click(function(){


$.post("my_session.php");

});

});


</script>




dont' forget to use session_start(); in the php file where u want  to play with session variables.

Commented:
one more thing, u must include the jquery library file in the head section.

<script type="text/javascript" src="js_folder/jquery_library_file.js"></script>

Author

Commented:

<script type="text/javascript">

$(document).ready(function(){

$("#my_link").click(function(){

$.post("change_session.php");

});

$("#my_button").click(function(){

$.post("my_session.php");

});

});

</script>

I Tried this but I can't get the variable to change.
In the PHP file is $_SESSION['searchmethod'] = 'search';

If I put a die('d'); statement in the php file it does not kill the page.
Does this mean it is not calling the file?

Author

Commented:
I think I see the Problem - I'm not passing the $_SESSION ID to the change_session.php file.
How do I refference the $_SESSION ID in javascript to pass to the php file?

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial