penisland Posted November 17, 2013 Share Posted November 17, 2013 (edited) 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 Edited November 17, 2013 by penisland Quote Link to comment Share on other sites More sharing options...
Solution JIXO Posted November 18, 2013 Solution Share Posted November 18, 2013 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¶2=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. Quote Link to comment Share on other sites More sharing options...
Rifts Posted November 18, 2013 Share Posted November 18, 2013 why not just pass in a variable to the php page then check if the var is there. If its there then run your function. Quote Link to comment Share on other sites More sharing options...
penisland Posted November 18, 2013 Author Share Posted November 18, 2013 why not just pass in a variable to the php page then check if the var is there. If its there then run your function. How would I do that? Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.