Marcus Lee
Marcus Lee

Reputation: 107

Sending data through AJAX to MySQL

So I'm trying to send dynamic generated data with AJAX to mysql.

 <script type="text/javascript">
   var postId;

   function getdata(){
       postId = document.getElementsByTagName("post-id");
   }
   function senddata(){
       var data = getdata();

       $.ajax({
            url: "php/count_shares.php",
            type: "POST",
            data: data,
            success: function(data){
             console.log(data);
         }
     });
   }
</script>

The function is done through onClick method per picture. I'm sending a string in the post-id tag. Then with count_shares.php my code is as follows:

$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$server = '';
$dbname = '';
$dsn = "mysql:host=".$server.";dbname=".$dbname;
$username = '';
$password = '';

 if (isset($_POST['data'])) {

   $click = $_POST['data'];

     $sqlcs = ("UPDATE posted_ad_img SET share_count = share_count + 1 WHERE post_id = $click");

   $dbcs = new PDO($dsn, $username, $password);
   $dbcs->$opt;
   $dbcs->prepare($sqlcs);

   $dbcs->execute();
}

But nothing is being sent to my database. Any help on this matter?

Upvotes: 1

Views: 706

Answers (2)

Sergey B.
Sergey B.

Reputation: 1019

Firstly - you don't return value from getData function. Need to change it

function getdata(){
   postId = document.getElementsByTagName("post-id");
   return postId[0].nodeValue;
}

Also you have to change your ajax request, something like this:

$.ajax({
        url: "php/count_shares.php",
        type: "POST",
        data: {data: data},
        success: function(data){
         console.log(data);
     }
 });

If you provide your html I can write more details

Upvotes: 0

Danish Bhayani
Danish Bhayani

Reputation: 409

Try this:

$.ajax({
        url: "php/count_shares.php",
        type: "POST",
        data: "data="+data,
        success: function(data){
         console.log(data);
     }
 });

Upvotes: 1

Related Questions