Jump to content

Sending mail using AJAX


darantes

Recommended Posts

Hi !

I am developing a web application that requires me to send mails through ajax.

The main problem I found is that I am trying to call my sendmail function written in javascript into an existing ajax request.

I will explain directly with the real code.

[!--coloro:#3366FF--][span style=\"color:#3366FF\"][!--/coloro--](An onclick event calls this function)
[!--fonto:Courier New--][span style=\"font-family:Courier New\"][!--/fonto--]function updateDB()
{
http.open('post', 'DBtasks.php');
http.onreadystatechange = verifyUpdateTable;
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
http.send('action=3&id='+trip_id+'& MY DATA');
}

function verifyUpdateTable()
{
if( http.readyState == 4 ) {
if( http.status == "200" ) {
var res = http.responseText;
if (res == '1') {

msg = 'test';
sendMail('myMail', 'my subj', 'my msg'); // so I am calling sendMail into this function that belongs to an ajax request

}
}
}
}[!--fontc--][/span][!--/fontc--]
[!--colorc--][/span][!--/colorc--]

[!--coloro:#009900--][span style=\"color:#009900\"][!--/coloro--](file: functions.js)

[!--fonto:Courier New--][span style=\"font-family:Courier New\"][!--/fonto--]var httpMail = createRequestObject(); // this is ok,, do not worry about it

function sendMail(to, subject, message)
{

httpMail.open('post', 'sendMail.php', true);
httpMail.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
httpMail.send('to='+to+'&subject='+subject+'&message='+message);
httpMail.onreadystatechange = verifySent;

}

function verifySent()
{
if( httpMail.readyState==4 ) {
alert(httpMail.status); // this alert shows an EMPTY STRING as the status and never goes into the next if
if( httpMail.status==200 ) {

var resp = httpMail.responseText;
alert(resp);

} else {

//displayMsg('Failed to send mail\n'+httpMail.statusText);
}
}
}[!--fontc--][/span][!--/fontc--]
[!--colorc--][/span][!--/colorc--]

[!--coloro:#993399--][span style=\"color:#993399\"][!--/coloro--](file: sendMail.php)

[!--fonto:Courier New--][span style=\"font-family:Courier New\"][!--/fonto--]<?php
$to=$_POST['to'];
$subject=$_POST['subject'];
$message=$_POST['message'];

$headers="Content-Type: text/plain; charset=iso-8859-1\n".
"From: atf@idh.com\n".
"Reply-to: atf@idh.com\n\n";

if(!mail($to,$subject,$message,$headers)){
echo 'NOK';
}
else{
echo 'OK';
}
return
?>[!--fontc--][/span][!--/fontc--]
[!--colorc--][/span][!--/colorc--]

[u]The results[/u]:
Once I make a test with this code I have no mail sent.

IF I try to call the sendMail javascript function out of the first ajax function ( verifyUpdateTable) it works perfectly.

So my issue really lays on the fact that I am calling the sendMail function into my first ajax verification function.

Anyone knows if it is possible to be this way ? otherwise, how could I send an email after updating my DB using ajax ? I cannot do it directly in PHP because the contents of my mail depends on the database update results.

Anyone has any suggestion ??? [img src=\"style_emoticons/[#EMO_DIR#]/huh.gif\" style=\"vertical-align:middle\" emoid=\":huh:\" border=\"0\" alt=\"huh.gif\" /]
[!--coloro:#CCCCCC--][span style=\"color:#CCCCCC\"][!--/coloro--] [!--colorc--][/span][!--/colorc--]
Link to comment
Share on other sites

Hi,,

hmm,.... the code seems ok there,,
Tested on my provider server with success,... (as mail function reports error using 'localhost'),,
[code]
<html>
<head>
<title>Testing,,</title>
</head>
<body>

<script>
var http = createRequestObject(); // this is ok,, do not worry about it

function updateDB()
{
    http.onreadystatechange = verifyUpdateTable;
    http.open('post', 'verif_tables.php', true);
    http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    http.send('pseudo=Hubert');
}

function verifyUpdateTable()
{
if( http.readyState == 4 )
    {
    if( http.status == "200" )
        {
        var res = http.responseText;
//        alert(res);
        if (res == '1')
            {
            sendMail('mymail@hotmail.com, 'testing', 'it should works,,'); // so I am calling sendMail into this function that belongs to an ajax request
            }
        }
    }
}

var httpMail = createRequestObject(); // yep,, still no worry;)

function sendMail(to, subject, message)
{
    httpMail.open('post', 'sendMail.php', true);
    httpMail.setRequestHeader('Content-Type','application/x-www-form-urlencoded; charset=UTF-8');
    httpMail.send('to='+to+'&subject='+subject+'&message='+message);
    httpMail.onreadystatechange = verifySent;
}

function verifySent()
{
if( httpMail.readyState==4 )
    {
    alert(httpMail.status); // this alert shows an EMPTY STRING as the status and never goes into the next if
    if( httpMail.status==200 )
        {
        var resp = httpMail.responseText;
        alert(resp);
        }
    else
        {
        //displayMsg('Failed to send mail\n'+httpMail.statusText);
        }
    }
}

function createRequestObject()
{
    var http;
    if(window.XMLHttpRequest)
    { // Mozilla, Safari, ...
        http = new XMLHttpRequest();
    }
    else if(window.ActiveXObject)
    { // Internet Explorer
        http = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return http;
}
</script>
<br>sending mail with Ajax,,<br>
<input type="button" value="send mail!" onclick="updateDB();">
</body>
</html>
[/code]
verif_tables.php file:
[code]
<?
// TODO your database connection
$result = mysql_query("SELECT test1 FROM test_database WHERE test1='".$_POST["pseudo"]."' ");
if(mysql_num_rows($result)>=1)
echo "1";
else
echo "bad";
mysql_close($db_link);
?>
[/code]
& the sendMail function is the same you've posted,...

So,, I haven't done some real changes from your original code,.... so, I don't understand why it doesn't work for you,... :s

Good luck with it,,

l8tr,,
Link to comment
Share on other sites

Thanks for testing... but I forgot to mention something that can be the reason of why it worked for you.

I am using Mozilla Firefox and it for some strange reason worked sometimes. I noticed it worked when we had a delay between the call of the two Ajax function (when I put an Alert when receiving the response of the first request).

On Internet Explorer it seemed to work almost the time, but it failled sometimes... I think it is something the browser can not handle or the use of two ajax requests in cascade was not take in account when the project of the browser.

Thank you!! [img src=\"style_emoticons/[#EMO_DIR#]/wink.gif\" style=\"vertical-align:middle\" emoid=\":wink:\" border=\"0\" alt=\"wink.gif\" /]
Link to comment
Share on other sites

To add,... I've also tested it yesterday with both IE & FF,... & worked fine for the 2 there,...
Maybe you should try something like:

-- do your 1rst ajax req & call the function A
--- func A
--- {
------ check if all is fine,,, [ if (res == '1') ],
---------- then, try to do directly add your 2nd request, (in the same function)
-----------httpMail.open('post', 'sendMail.php', true);
---------- etc,,

just an idea,,

l8tr,,

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.