September 21, 2012

Ajax Give Response but not Executing the PHP Service

Question by Hatem

Am doing Ajax request to a file which sends a mail. It give me the correct response which is “Message Sent” but the mail not sent. When I try to execute that file from the browser with the same GET Headers , it send the mail.

So what’s the problem here ?

The ajax request working well and triggered using (success) keyword in jquery to make sure that it succeed.

Help me !

For ajax side :

function SendEmail(To, Subject, Message) 
{
 var URL = 'mail-service.php?to=' + To + '&subject=' + Subject + '&msg=' + Message;

$.ajax({
    url: URL,
    type: 'GET',
    success: function (res) {
        alert("Message Sent to : " + To);
    }
});
  }

for PHP side :

<?php
$url = "http://mydomain.com/mail/mail.php?to=".$_GET['to']."&subject=".$_GET['subject']."&msg=".urlencode($_GET['msg']);

$link = fopen($url,"r");

while($res = fread($link,100))
{
    echo $res;
}

fclose($link);
 ?>

Answer by Starx

You misunderstood the function, The success function of the AJAX request executes once the request is successful, it does not care about what the page requested to did or did not.

To ensure you receive correct messages, you have to setup your PHP processing file, to return the response.

In your script

success: function (res) {
    alert(res); //Display the response text
}

And make sure your PHP file, return the response text as output.

while($res = fread($link,100))
{
    echo $res; //Make sure this is like "Message sent" or "Message sending failed"
}

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!