Button Onclick calls Javascript which calls a PHP file which adds to a Mysql database

我只是一个虾纸丫 提交于 2019-12-03 17:21:17

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...
}

I would recommend jQuery,

this is what you need: http://api.jquery.com/jQuery.get/

function add(title,text) {
  $(function() {
    $.get("add_to_db.php?title="+title+"&text="+text);
  });
}

and you can do it in a more advanced way using http://api.jquery.com/jQuery.post/

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