Avadhesh18
Avadhesh18

Reputation: 37

send data using ajax and then send email

I am trying to create a script that will send a email to our company email when someone clicks a button. The html will be hosted on a static page and will do everything client side, whereas the php code will be hosted on another domain.

What I have tried so far is.

HTML

<head><title>Report Errors</title>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js' type='text/javascript'></script></head>
<script>$(".c").click(function(){
var href = this.href;
        $.ajax({
        url: 'http://example.com/m35.php',
        type: 'POST',
        data: { subject: href },
        success: function (data) {
                    setTimeout(function (){
                    $(".container").html(data)
                    }, 1000)
                }
        });
    })
</script>

<a href="http://link-to-be-sent.example.com" class="c">send</a>
<div class="container">success</div>

And the code in m35.php file -

<?php  

$mailTo = "[email protected]"; 
$mailFrom = "[email protected]";  
$subject = $_POST["subject"];
$message = "someone reported the content in subject doubtful.";  


mail($mailTo, $subject, $message, "From: ".$mailFrom);  
?>

EDIT : Based upon comments I want to clarify that it is even not working on same domain and directory, However this type of code is also working but how to do that without page reload with javascript/jquery.

<form method="post" action="http://example.com/m35.php">
<input type="text" name="subject" id="subject" value=""> <input type="submit">
</form>

Upvotes: 0

Views: 2015

Answers (1)

py3r3str
py3r3str

Reputation: 1879

Click event is attached before dom element is render. So it isn't fired. $(".c") is a html element so after click, it will load another page. In that case ajax request may not reach the server. To prevent this js code should be in $( document ).ready() event and use return false; from click event to block page load:

<script>
$( document ).ready(function(){
    $(".c").click(function(){
        var href = this.href;
        $.ajax({
            url: 'http://example.com/m35.php',
            type: 'POST',
            data: { subject: href },
            success: function (data) {
                setTimeout(function (){
                    $(".container").html(data)
                }, 1000);
            }
        });
        return false; // prevent load to another page
    });
});
</script>

Upvotes: 2

Related Questions