I am trying to send the ID of an element, stored in a variable to my PHP file, but it's not sending it. The alerts in my JS file go off, so the problem doesn't seem to be there. When I hit submit to send my email, the 'email' variable does send but the 'band' goes empty. Where could my error be?
HTML LIST
<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
<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("[email protected]", "Subject Title",$band,"From: $email");
header("Location: ../index.php");
alert('success');
1 Answer 1
You are not sending the data to the server with the Ajax call, the form is submitting. You need to cancel the form submission. Also you are not sending up the email, only tBand.
$("#submit").click(function(e){
e.preventDefault();
$.ajax({
url: "sendmail.php",
type: "post",
data: {
"tBand": tBand,
"email", $("[name='email']").val()
}
});
});
Also you probably want to remove the click if you are assigning it multiple times
$("#submit").off("click").on("click", function(e){
.ajax
doesn't get the chance to submit it since<form>
is submitting it first?