In my MySQL database there is a column for VideoID and VideoCode
I have a PHP function in backend.php that aims to pick the next video in the list as follows:
$VideoID = 0;
function nextvideo(){
global $VideoID;
$VideoID = $VideoID + 1;
$sql = mysql_query("SELECT * FROM Videos WHERE VideoID = '".$VideoID."'");
$result = mysql_fetch_array($sql);
return $result[2];
}
$VideoCode = nextvideo();
I then have the $VideoCode variable echo in my front end file inside a url that gives the embedded video.
That is all fine and it works, each time the nextvideo() function is called it picks the next $VideoCode correctly. However I want to implement a ‘next’ button that allows the user to effectively call the nextvideo() function and therefore load the next video. So I know i need to use AJAX and the .get() function but I have no idea how to use it and have tried reading up on it. So far I have this:
<script type="text/javascript">
function next() {
$.get("backend.php", *1*, *2*);
return false;
}
</script>
<a href="#" onclick="next();">Next</a>
I know that after backend.php in the $.get() function i need some more info, *1* being something to send to the backend file and *2* being what to do with the result once its sent back. This is where I am stuck.
Does *1* need to be nextvideo() because that’s the PHP function i wish to call, then *2* be something that will refresh the page so that the $VideoCode variable is updated and the next video is updated? Reading the documentation i know it needs to look something like:
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});
But what is function(data)?
function(data)is a javascript function which is called when the request completes, passing in the variabledatawhich is the page returned from the server. So in other words, when the request completes the code in that function will be executed and the variabledatawill contain whatever the server sent back from your request.What you want to do is something like this
Where you have a hidden input field with id
videoIdwhich has a value of the current video’s id and an element with idvideowhich is the element to be updated with the new video.Your PHP script would look something like this:
This accepts the $_GET variable being passed in by the AJAX function and prints out the video code which is sent to the
datavariable in the javascript.Hopefully this helps, if you’re still unsure of anything please ask!