I'm a noob to jquery and ajax, so please bear with me :) I want to call a php script that sends out an email when a button is clicked. I do not need to pass any data to the PHP page. Below is my jquery code:
<script>
$(document).ready(function(){
$("#flagbutton").click(function(){
// call php script here
$("#div1").hide();
$("#span2").text("Thanks for clicking!");
});
});
</script>
<div style="float:right" id="div1"><span id="span1">Click the button</span>
<button id="flagbutton">The button</button></div>
<span style="float:right" id="span2"></span>
Below is my php code:
<?php
$to = "somebody@somebody.com";
$subject = "Subject";
$message = $_SERVER['HTTP_REFERER'];
$headers = "From: test@somebody.com";
mail($to,$subject,$message,$headers);
?>
Where and how do I call the php script? Thanks!
Using AJAX, you can do what you wanna achieve. The code below does it exactly!
$("#flagbutton").click(function(){
$.post("php.php", function(){
$("#div1").hide();
$("#span2").text("Thanks for clicking!");
});
});
Or, you can do this way:
$("#flagbutton").click(function(){
$.post("php.php").done(function(){
$("#div1").hide();
$("#span2").text("Thanks for clicking!");
});
});
$.post("path_to_php",{}).done(function(data)
{
//ajax completed, the variable data will return which the PHP will echo out.
});
<script>
$(document).ready(function(){
$("#flagbutton").click(function(){
$.ajax({
url: your_url,
beforeSend: function() {
// you can show some loading things
},
complete: function() {
//remove the loading things here
},
success: function(response) {
$("#div1").hide();
$("#span2").text("Thanks for clicking!");
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "
" + xhr.statusText + "
" + xhr.responseText);
}
});
});
});
</script>