2012-02-26 8 views
2

ボタンがクリックされた場合に聴くにはAJAXが必要です。次に、PHPスクリプトを実行する必要がある場合私は、AJAXが正しくボタンクリックを聞いていないので、スクリプトを実行しないという問題があります。
私のコードに誤りがありますか?
どうすればいいですか?Ajaxボタンのイベントを聞きますクリックしてからPHPファイルを実行します

ボタン:

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

AJAXそれは呼び出します(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ファイル(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); 
} 
?> 
+0

$ 'には' method'プロパティがありません:ajaxコールのhttp://jsfiddle.net/sbybd/

例。 ajax'。 'POST'か' GET'かを判断する 'type'があります。とにかく、「正しく聞いていない」ということはどういう意味ですか?あなたはどんな種類のエラーを起こしているのですか、何も起こりませんか? –

+1

addtofavorites.phpスクリプトは実行されません。クリックすると何かをするために参照したにもかかわらず、ボタンは何もしません。 –

答えて

1

click機能を書き換えてみてください。

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

その後favfunct

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

あなたfavfunctランニングを取得する必要があります。その後、必要に応じてコードをさらにデバッグすることができます。

また、ボタンからonclickを取ることができます。

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

フィドルのデモ:

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

AJAXを正常にPHPファイルを呼び出してデータベースに追加する方法を知りたいですか? –

+0

@JulianNeill正しく書く必要があります。詳細については、[jquery docs](http://api.jquery.com/jQuery.ajax/)を参照し、例を含めるように答えを更新しました。 –

+0

ありがとうございました –

関連する問題