Send mail server site client uses javascript

jophosti

New Member
Messages
1
Reaction score
0
Points
0
I am new on PHP, CGI. I have a website running and want to send email to a fixed addres The subject and body of the mail message are collected during a visit by javascript.
I am looking for some example code. Javascript on the client and PHP/CGI on the server site.
Thanks in advance.
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
Read the links in my sig and follow the guidelines.
 

kloadx10

New Member
Messages
24
Reaction score
0
Points
0
You can't send an email directly from javascript but there are some tricks
Code:
if(document.ready){
window.open('mailto:test@example.com?subject=subject&body=body');
}
or you can use jquery's post method here is how you can do it??
create 2 pages index.html and mail.php

in the index.html write
Code:
$(document).ready(function(e){
$.post("mail.php", {q: 'mail', subject: $('#subject').val(), body: $('#body').val()}, function(data){
	$('#thanks').html(data);
});
}
now what does this do, it will post the subject and body content to mail.php and then from there you can send the email here is another example and remember $('#subject').val() and $('#body').val() are ID's replace then with what ever content you want.

mail.php
Code:
if(isset($_POST['q'])){
$to = 'youremail@example.com';
$subject = mysql_real_escape_string(filter_var($_POST['subject'], FILTER_SANITIZE_STRING));
$body = mysql_real_escape_string(filter_var($_POST['body'], FILTER_SANITIZE_STRING));
$headers = 'From: webmaster@example.com' . "\r\n" .
    'Reply-To: webmaster@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $body, $headers);
}

this will send the email hope you find it useful.
 
Last edited:

miguelkp

Member
Messages
304
Reaction score
7
Points
18
Yes, I also think jQuery is definitely 'the way to go', if I've undestood well your problem.
Give this a try:
http://jquery.malsup.com/form/

It's essentially what kloadx10 said but a bit more customizable. I found the ajaxSubmit the best way to deal with advanced and dynamic contact forms (visit the above link, clic on 'Examples' tab and choose 'ajaxSubmit' to see demo code). In fact I've used that method in a (now closed) website and I'm using it in a website that should be deployed soon.

Really versatile and with the JS/client + PHP/server approach you're looking for. You can even send info to a html div tag ("e-mail is wrong", "you need to write a message", "read our ToS before sending the form", "choose at least one option", "everything was ok and the mail was sent" and so on) to dynamically guide the end-user. And without needing to reload entire page (only that little div via ajax), a thing that is very important sometimes.
 
Top