简体   繁体   English

单击按钮时使用PHP + jQuery

[英]Use PHP + jQuery when click on a button

I have a button on my page : 我的页面上有一个按钮:

<button class="play"></button>

When I click on it, it launches the video via jQuery 当我点击它时,它通过jQuery启动视频

$('.play').on('click',function(){
    player.play();
});

But I also want to add PHP code to save the user ID in the database when he clicks on that button. 但我还想添加PHP代码,以便在单击该按钮时在数据库中保存用户ID。

How can I mix PHP & jQuery? 我如何混合PHP和jQuery? I'm not used to Ajax, is it the solution? 我不习惯Ajax,是解决方案吗?

Thanks for your help! 谢谢你的帮助!

add a function: 添加功能:

function add_to_db(user_id){
    $.post('add.php', {userId: user_id}, function(response){
        //do something with the response
        r = JSON.parse(response);
        if (r.status === 'error'){
        //handle the error
        alert(r.message);
        }
    });
});

when you play do the following 当你玩的时候做以下事情

$('.play').on('click',function(){
    player.play();
    user_id = //however you chose to set this in the page
    add_to_db(user_id);
});

your add.php: 你的add.php:

//perform your db update or insert
//if successful:
$response['status'] = 'success';
//else:
$response['status'] = 'error';
$response['message'] = 'update was not successful';
//look into try/catch blocks for more detailed error messaging.

//then send the response back
echo json_encode($response);

Try using ajax 尝试使用ajax

 $('.play').on('click',function(){
    player.play();
    $.ajax({
      type: "POST",
      url: "some.php",  // your php file name
      data:{id :"id"}, //pass your user id
     success:function(data)
    {
   if(data==true)
    alert("success");
else
  alert("error");
    }
    });
    }

some.php some.php

<?php
$success=false;  //Declare and initialize a variable 

// do your code to update your database
//and check if the database is updated , if so set $success=true

echo $success;


?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM