Tag: ajax

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.