PHP/AJAX: Call PHP function by clicking a link

This tutorial demonstrates how to execute an external PHP function by clicking a simple link within HTML. The method uses AJAX so that the page doesn’t refresh and doesn’t require a form submission.

1) Paste the following code into a .js file. For demonstration purposes, we have named it “ajax_link.js”.

Select Code
/*
* ajax_link.js
* chriscook.me
*/

function loadurl(dest) {

try {
// Moz supports XMLHttpRequest. IE uses ActiveX.
// browser detction is bad. object detection works for any browser
xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// browser doesn't support ajax. handle however you want
}

// the xmlhttp object triggers an event everytime the status changes
// triggered() function handles the events
xmlhttp.onreadystatechange = triggered;

// open takes in the HTTP method and url.
xmlhttp.open("GET", dest);

// send the request. if this is a POST request we would have
// sent post variables: send("name=aleem gender=male)
// Moz is fine with just send(); but
// IE expects a value here, hence we do send(null);
xmlhttp.send("null");
}

function triggered() {
if ((xmlhttp.readyState == 4) (xmlhttp.status == 200)) {

document.getElementById("ajaxlink").innerHTML = xmlhttp.responseText;
}
}

2) Next, add the following code in the section of your HTML file.

Select Code
<script src="ajax_link.js" type="text/javascript"></script>

3) The following code should be placed in the HTML body of a PHP file.

Select Code
<div id="ajaxlink" onclick="loadurl('ajax_function.php')">Click Here</div>

Replace ‘ajax_function.php’ with the correct file you want to execute. For instance, if you want your users to “click here” in order to send themselves a copy of their monthly invoice, you’d code the mailer function in ‘ajax_function.php’.

4) That’s it. Ensure that you keep the <div> id as “ajaxlink”. Once you click the link, it will disappear (until the page is refreshed).

Feedback: I’d love to hear how you’ve used this tool. Please feel free to post a comment on my blog.

Disclaimer: This tutorial is provided to demonstrate how to perform the function. Please ensure that you review the code and add security measures before using this in a production environment.

6 comments on “PHP/AJAX: Call PHP function by clicking a link

  1. Devin Walker says:

    Very Helpful thanks!

  2. Iain Munro says:

    Morning

    Should that be ajax_click.js instead of ajax_link.js in the HTML code ?

    Iain

  3. You illuminated me, I was very lost with AJAX, i’m using it in http://www.forospinning.com/musica for voting the favorite songs. Now I added the location.reload(); after the send() but it scrolls the page up. Is there any way to reload keeping the scrolling position? like location.reload(#anchor); or something?

    Thankyou

  4. Hi Chris,

    Your short script is a real help and is working fine.

    Because I’m implementing this inside an tag in a Galleria image viewer, I can not use any double quotes in the onclick call.

    On a simple test page, (no tags) when I replace only one set of the double quotes, it works OK:

    Click Here

    However when I replace the double quotes around the onclick call as well, like this:

    Click Here

    It won’t work. I also tried " and that won’t work either.

    Any ideas?

    Thanks,

    Jerry Kornbluth

  5. vikas says:

    Very useful.
    Make the task simpler by providing download.zip file

    Normally i download the code .. see the result and then understand…

    that is my way …
    But really nice

  6. Anna says:

    Thank you.

    P.S You forgot && operator in: function triggered()
    line: if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200))
    It took me some time to understand why this code was’n worked.

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>