Update database info with onclick button

怎甘沉沦 提交于 2019-12-02 16:46:44

问题


I need some help with a button onClick.

<button type="button" id="1" onclick="this.disabled=true; ^FUNCTION TO UPDATE^"> 
<button type="button" id="2" onclick="this.disabled=true; ^FUNCTION TO UPDATE^"> 
<button type="button" id="3" onclick="this.disabled=true; ^FUNCTION TO UPDATE^"> 

With this code I disable the button that was pressed, but I also need to update info in a database sending the id, something like this:

UPDATE reservation SET status='approved' WHERE id=^ID OF THE CLICKED BUTTON^

I need it to be loaded in the same page without sending it with POST or GET.


回答1:


Use ajax call for this eg:

$.get('update_reservation.php', {id: 1});

see http://api.jquery.com/jQuery.get/ for more info.




回答2:


With plain javascript you can do something like this:

<script type="text/javascript">
<!--
var page = "dbupdate.php"; // hardcode this elsewhere out of sight

function update(target,data){
document.getElementById(target).innerHTML = 'sending...';
if (window.XMLHttpRequest) {
       req = new XMLHttpRequest();
       req.onreadystatechange = function() {ajaxDone(target);};
       req.open("POST", page, true);
       req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
       req.send("data=" + data );
   // IE/Windows ActiveX version
  } else if (window.ActiveXObject) {
       req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req) {
           req.onreadystatechange = function() {ajaxDone(target);};
           req.open("POST", page, true);
           req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
           req.send("data=" + data );

       }
   }
}  

function ajaxDone(target) {
    // only if req is "loaded"
    if (req.readyState == 4) {
        // only if "OK"
        if (req.status == 200 || req.status == 304) {
           results = req.responseText;
            document.getElementById(target).innerHTML = results;
        } else {
           document.getElementById(target).innerHTML="ajax error:\n" +
            req.statusText;
        }
    }
}
// -->
</script>

For output make sure you have a div with the id equal to target.



来源:https://stackoverflow.com/questions/6559868/update-database-info-with-onclick-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!