簡體   English   中英

使用AJAX將變量發送到PHP

[英]Sending variable to PHP with AJAX

我正在嘗試將存儲在變量中的元素ID發送到我的PHP文件中,但是沒有發送它。 我的JS文件中的警報不可用,因此問題似乎不存在。 當我點擊“提交”以發送我的電子郵件時,“ email”變量確實發送但“ band”為空。 我的錯誤在哪里?

HTML列表

<div class="artistn">
        <li class="highlight" id="Mitski"> <span class="left gone">Mitski</span>
          <audio controls>
            <source src="songs/exsong.mp3" type="audio/mpeg">
            <source src="songs/exsong.mp3" type="audio/ogg">
            <embed height="50" width="100" src="horse.mp3">
          </audio>
        </li>
      <li id="AdultMom"> 
        <span class="left">Adult Mom</span>
        <audio controls>
          <source src="songs/exsong.mp3" type="audio/mpeg">
          <source src="songs/exsong.mp3" type="audio/ogg">
          <embed height="50" width="100" src="horse.mp3">
        </audio>
      </li>
</div>

HTML表格

<form method="post" action="js/sendmail.php">
    <label> Your Email </label> <input type="text" name="email"></input>
      <input  id="submit" type="submit" value="Submit" class="button">
 </form>

JS

$( "li" ).click(function() {
  $('.highlight').removeClass('highlight'); 
  $( this ).toggleClass( "highlight" );
  var  tBand = jQuery(this).attr('id');
  alert(tBand);
      $("#submit").click(function(){
        alert(tBand);
        $.ajax({url: "sendmail.php", type: "post", data: {"tBand": tBand}})  
      });
});

PHP

$email = $_POST['email'];
$band =  $_POST['tBand'];

mail("example@email.com", "Subject Title",$band,"From: $email");
header("Location: ../index.php"); 
alert('success');

表單正在提交,您沒有通過Ajax調用將數據發送到服務器。 您需要取消表單提交。 另外,您不發送電子郵件,僅發送tBand。

$("#submit").click(function(e){
    e.preventDefault();
    $.ajax({
        url: "sendmail.php", 
        type: "post", 
        data: {
            "tBand": tBand, 
            "email", $("[name='email']").val()
        }
    });  
});

另外,如果您多次分配點擊,您可能希望將其刪除

$("#submit").off("click").on("click", function(e){

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM