Julian Neill
Julian Neill

Reputation: 117

Ajax Listen Event on a Button Click then Runs a Php file

I need the AJAX to listen to if a button is click. Then if it is I need it to run a PHP script. I am having troubles by the AJAX not correctly listening to the Button Click and so it never runs the script.
Any Error in my code you may see?
Any advice on how I should do this?

The Button:

<input id="button_1" type="button" value="favorites1" onclick="favfunct();" />

The AJAX that calls it is: (ajaxlisten.js)

<script type="text/javascript">

    $(document).ready(function () { // Make sure the elements are loaded on the page
        // Listen for a click event on the button
        $('#button_1').click(favfunct);
    });

    function favfunct(e) {
        // Stop the page from "following" the button (ie. submitting the form)
        e.preventDefault();
        e.stopPropagation();

        // Call an AJAX function to the proper page
        $.ajax("js/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.
                alert ("successfully loaded")
            }          
        });
    }
</script>

Php File (addtofavorites.php)

<?php
$con = mysql_connect("localhost","root","student");

if ($_POST["action"] = 'favorites1')
{ 
    if (!$con);
    {
        die('Could not connect: ' . mysql_error());
    }                   
    mysql_select_db("tvid", $con);

    $sql="INSERT INTO tv (userid, favorites) VALUES (345,77);"
    if (!mysql_query($sql,$con));
    {
        die('Error: ' . mysql_error());
    }
    echo "Your Video was Added To Your Favorites";
    mysql_close($con);
}
?>

Upvotes: 2

Views: 14676

Answers (1)

jk.
jk.

Reputation: 14435

Try rewriting the click function:

$(document).ready(function () { 
   $('#button_1').click(function(e){
        e.preventDefault();
        e.stopPropagation();
        favfunct();
   });
});

Then the favfunct:

function favfunct() {
// AJAX Call Below
// rest of your code

That should get your favfunct running. After that you can further debug the code if necessary.

You can also take the onclick off the button:

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

Fiddle demo: http://jsfiddle.net/sbybd/

Example of ajax call:

$.ajax({
     type: "POST",
     url: "js/addtofavorites.php",
     data: { "get" : "runfunction", "action" : "favorites1" },
     success: function (response) {
         alert ("successfully loaded");
     }    
 });

Upvotes: 1

Related Questions