Before someone has a go at me or marks this down, I have looked all over the internet to find out how to do this (including the same question on stackoverflow). I'm new, and I am finding it very hard to learn new concepts so please be easy on me.
What I want to do is call a php script/function on a button click. I have this running in WAMP if that helps. Here's my code:
<?php include 'the_script.php'; ?>
<button type="button" onclick="the_function()">Click Me</button>
the_script.php has this in it:
the_function() {
echo "You win";
}
Why isn't this working? I've heard about the button being client side etc. and PHP being server-side, which means that you cannot link the two together. I know that you have to use AJAX to make this work, however I legitimately have absolutely no clue how to do it. I've tried googling it etc., however I can't find anything. I know how to use AJAX and call events with it, however I still have no idea how to make it call a PHP script.
Can you please make your answers as clear and simple as possible, I'm new to this
Thanks for the help :)
EDIT ***
For some reason wherever I go everyone's code is different. The way I have been taught AJAX looks completely different. Can you please write it this way so I can understand? Thanks, here's an example:
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
request.open('GET', 'file.php', true);
request.onreadystatechange = function() {
if (request.readyState===4 && request.status===200) {
do stuff
}
}
request.send();
Because PHP only responds to requests (GET, POST, PUT, PATCH, and DELETE via $_REQUEST) this is how you have to run a php function even though their in the same file. This gives you a level of security, "Should I run this script for this user or not?".
If you don't want to refresh the page you can make a request to PHP without refreshing via a method called Asynchronous Javascript and XML (AJAX).