I am completely new to Ajax and jQuery in practical terms, but I'm trying to make a subscribe button for my site using both.
Now I have read most of the documentation to Ajax and jQuery and have come up with a little code to do just that.
The problem is that it isn't working and I can't for the life of me see why.
I click the subscribe button and nothing happens:
The subscribe.php script doesn't run and the database isn't updated and no alert is showing - like I said... nothing happens
Hope someone can help.
Code so far
jQuery.js (loaded in the index.php that holds all other pages at the start of the body-tag)
<body>
// Load official jQuery-library
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
// Load my own jQuery-script file
<script src="jQuery/jQuery.js"></script>
.
.
.
// Load all pages (videos.php, channel.php,...) as needed
</body>
// Code in my own jQuery.js
$(document).ready(function(){
"use strict";
$("#subscribe").click(function(subscribeData){
$.ajax({
type: "POST",
url:'../scripts/subscribe.php',
data:{randomStringUser:subscribeData},
dataType:'json',
success:function(data){
alert("You subscribed");// Do what you do after subscribe.php has done it's thing
// just to test I just put an alert here
},
error:function(){
alert("Didn't work");// Do what you do if mission failed
// just to test I just put an alert here
}
});
});
});
PHP on top of the page where the subscribe button is located (ie. channel.php) and subscribe-button code
<?php
.
.
.
$randomStringUser = $_GET['channel'];
$subscribeData = json_encode($randomStringUser);
?>
// Page html
.
.
.
// Subscribe-button
<button type="button" class="btn btn-success" id="subscribe">
Subscribe
</button>
subscribe.php from the ajax-call
<?php
session_start();
$randomStringUser = $_POST['randomStringUser'];
// $_SESSION['id'] is set with users-id when user log in
// So if user logged in use that id as $subscriberID
if ( isset ( $_SESSION['id'] ) ) {
$subscriberID = $_SESSION['id'];
}
"SELECT id FROM userinfo WHERE randomString = ? LIMIT 1" // using $randomStringUser as ?
// Use the id found in SELECT as $subscriptionID
"INSERT INTO usersubscription ( subscriberID , subscriptionID ) VALUES ( ? , ? )" // Using $subscriberID and $subscriptionID from above as ?