0

I have a javascript that plays an audiofile from a list of files when a link is clicked. Page is not reloaded and it works fine.. so far. Now i'd like to trigger a sql insert query that will update my database with info on what audiofile was played. Since i use e.preventDefault im not loading any new page hence i cannot trigger a sql run that way. How do i go about this? My page is a mix of php and javascript. Below is the javascript part. Please give me some advice or direction cause i dont know where to start.

function audioPlayer(){
            $(document).on("click", "#playlist a", function(e) { 
               e.preventDefault(); 
               $("#audioPlayer")[0].src = this;
               $("#audioPlayer")[0].play();
            });
    }
3
  • Have you tried making an ajax request to your server? It doesn't require a page refresh and it can be triggered by the click event. Commented Apr 5, 2018 at 17:52
  • Mary Jane's recommendation is my answer below Commented Apr 5, 2018 at 17:56
  • You want AJAX with JQuery... You can post to a web service. Commented Apr 5, 2018 at 18:09

1 Answer 1

0
$.post("savetodb.php", {key:value, key2:value2, etc:stuff},       
function (status, data){
if(status == "success"){
console.log(data);
}
});

Data is whatever you echo out on your php file that save to DB. Key is the $_POST['key'] like a form is... Just like key2 and etc are keys. So you pass it just like form data.

Or you can use $.get() instead or $.ajax() method too

Hope this helps :)

The console log of data can be where you do whatever u wanna do after it's saved to DB.

In savetodb.php you would just have:

if(isset($_POST['key'])){ 
// save value of post to DB 
// if save is successful:
echo "I did something good."; 
}

Your console log of data would say "I did something good."

Sign up to request clarification or add additional context in comments.

2 Comments

thanks :) but all of this goes inside the audioPlayer() function?
The $.post does yes, but the PHP file is separate

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.