1

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?

3
  • please echo query error to see whats wrong Commented Jun 22, 2015 at 2:56
  • 1
    Your function getdata() does not return anything, so your var data will be null. Try adding return postId; at the end of the function. Commented Jun 22, 2015 at 3:10
  • 1
    getElementsByTagName("post-id"); is invalid. post-id isn't any html element. It should be specific to html elements like input,button,select etc!! Commented Jun 22, 2015 at 3:24

2 Answers 2

1

Try this:

$.ajax({
        url: "php/count_shares.php",
        type: "POST",
        data: "data="+data,
        success: function(data){
         console.log(data);
     }
 });
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.