drnx3715 2012-02-25 18:11
浏览 199
已采纳

按钮Onclick调用Javascript调用PHP文件,该文件添加到Mysql数据库

I need help with adding to a database. I want to call a javascript scrt from a button click method. The Javascript Script, I want to call upon a php file which contains some code that adds to a MySQL Database.

I literally tried over 20+ website and No help with the stuff.

If AJAX would be better Could you help me?

The Button Code:

<input type="button" value="favorites1" onClick="favfunct();"> 

The Javascript Code

function favfunct() {
    var target = document.createElement( "script" );
    target.setAttribute( "src", "php/addtofavorites.php" );
    document.getElementsByTagName( "body" )[0].appendChild( target );`
}

The Php Code

<?php
    echo "test successful"
    $con = mysql_connect("localhost","root","student");
    if ($_POST["get"] == 'runfunction')
        echo "Works";
    }
    if ($_POST["action"] == 'favorites1'){ 
        echo "Testing Was Successful"
        if (!$con)
        {
            die('Could not connect: ' . mysql_error());
        }                   
        mysql_select_db("tvid", $con);
        $sql="INSERT INTO Persons (userid, davorites) VALUES 
            ('1','$_POST[video0]')";
        if (!mysql_query($sql,$con))
        {
            die('Error: ' . mysql_error());
        }
        echo "Your Video was Added To Your Favorites";
        mysql_close($con)
    }
?>
  • 写回答

2条回答 默认 最新

  • dongmi5177 2012-02-25 18:39
    关注

    So, this "works" the same way that hammering a screw in does. It will get in there, but not really the way you want to do things.

    Don't use a script tag to trigger a php page. Your page will trigger, but it is the wrong tool to get the job done. You want to use AJAX. AJAX was specifically made for this purpose while a script tag was meant for running scripts on the page. It will try to fetch the contents of addtofavorites.php but it will expect JavaScript as the return. And you won't be able to use $_POST since you have no way to post data to the request.

    Instead, use AJAX. If you are already using a JavaScript library, then it will have a nice AJAX wrapper for you (I don't know of a single library off the top of my head that doesn't). You can check out the API documentation for you given library for documentation on how to use the AJAX functionality (jQuery, Prototype.js, Mootools, etc.).

    As an example, I will use jQuery, because it is one of the most popular ones. Here is a request using jQuery to your page (and what looks to be expected variables)

    // Call an AJAX function to the proper page
    $.ajax("php/addtofavorites.php", {
            // Pass our data to the server
            data: { "get" : "runfunction", "action" : "favorites1" },
            // Pass using the appropriate method
            method: "POST",
            // When the request is completed and successful, run this code.
            success: function (response) {
                    // Successfully added to favorites. JS code goes here for this condition.
                }
        });
    

    Also, as a side note, every line in PHP needs a semicolon ; at the end of it. Many of yours don't. And the 3rd line is missing an opening bracket { though I'm not sure if that is just an artifact of your copy paste or not.

    Addendum

    I would recommend using jQuery to listen for events as well. The events API for jQuery will let you listen for events on objects. So, something like this:

    <input id="button_1" type="button" value="favorites1" />
    

    and the jQuery

    $(document).ready(function () { // Make sure the elements are loaded on the page
        // Listen for a click event on the button
        $('#button_1').click(favfunct);
    });
    // Now define the function
    function favfunct(e) {
        // Stop the page from "following" the button (ie. submitting the form)
        e.preventDefault();
        e.stopPropagation();
        // Insert AJAX call here...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行