Jump to content

Simple call of php function using ajax


penisland

Recommended Posts

I would like to know how to call a php function using javascript. I've done some googling and found that I need to use ajax. I read some tutorials and don't understand how to use ajax.

 

All I want to do is execute a php function, which writes to a txt file, from the execution of a javascript function. I don't care if the webpage refreshes or not; I'll just make the javascript function refresh the page.

 

Something like this:

<?php include 'banusers.php'; ?>
<script>
function banUser()
{
<?php writeIPToFile(); ?>
alert("You have been banned!");
window.location.reload();
}
</script>

<p>Click <a href="javascript:banUser();">HERE</a> to ban yourself!</p>

Would someone be kind enought to write an example for me?

 

Edit: fixed typo

Link to comment
https://forums.phpfreaks.com/topic/284003-simple-call-of-php-function-using-ajax/
Share on other sites

Hello penisland,

 

Just to be clear, I don't know if its possible to call a function by its name form ajax script, but you can call a .php page, consider index.html :

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
var a = new XMLHttpRequest();
a.open("GET","test.php");
a.onreadystatechange = function() {
if( a.readyState == 4) {
if( a.status == 200) {
alert("Worked");
}
else alert("HTTP error "+a.status+" "+a.statusText);
}
}
a.send();
</script>
<title>Ajax call to PHP</title>
</head>
<body>
</body>
</html>

AJAX will send a GET reguest to test.php which is placed in the same directory as index.html, now consider this code for test.php

<?php

// Defining the function banUser()

function banUser() {
    // Code .....
}

// Executing banUser()

banUser();

?>

This way test.php takes care of executing the banUser() method.

 

You can also pass get parameters to test.php, in the AJAX script

a.open("GET","test.php?para1=val1&para2=val2");

Then you can handle these values from PHP's $_GET super global.

 

I'm goning to make a personal note about these lines of codes I've wrote, they're just poor examples with alot of security flaws,

try to learn about AJAX before adding pieces of code that might damage your site.

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.