简体   繁体   中英

JQuery Ajax response not working | Php

I have a code like this

<script type="text/javascript">

function email(){
var myTextField = document.getElementById('email_hidden').value;
//alert(myTextField);
$.ajax({    
    type: "POST",
    url: "sendmail.php",
    data: "email_user="+myTextField,
    success: function(response){
    alert(response);    

}
});
}
</script>

My sendmail.php code is like this.

    <?php
    $to = $_REQUEST['email_user'];
    $headers  = 'MIME-Version: 1.0' . "\r\n";
    $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
    $headers .= "From: Haan Test<haan@gmail.com>\r\n";
    $message_body = "Your Details";
    $subject = "Check mail";
    mail($to, $subject, $message_body, $headers);
    echo "success";
    ?>

and my html looks like this.

   <div id="email_hide"><a href="#" onclick="email()" >Send Email</a></div>

I am getting the response in my firebug console as success but i could not alert the response. I can receive the mail also for the above jquery ajax functionality(sendmail.php)

In other words, how to alert the response after ajax call.. I have tried onComplete also. plz help me with this.

My Scenerio is like this: User page(index1.html) >> Paypal Sandbox (for transaction) >> User page(index2.html) Here in index2.html, i fetch last transaction details from paypal sandbox with a send mail at the top right corner, so when user clicks the send mail(anchor tag) the mail should be sent via ajax jquery call.

Thanks Haan

If ur datatype is json ,then try this

<script type="text/javascript">

function email(){
var myTextField = document.getElementById('email_hidden').value;
//alert(myTextField);
$.ajax({    
    type: "POST",
    url: "sendmail.php",
    data: "email_user="+myTextField,
     dataType: "json", 
    success: function(response){
    alert(response);    

}
});
}
</script>

Try add

$.ajax({    
   type: "POST",
   url: "sendmail.php",
   data: "email_user="+myTextField,
   success: function(response){
      alert("Success\n" + response);    
   },
   error: function(errMsg) {
      alert("Error\n" + errMsg);
   }
});

and see which one gets called.

Try using the shorthand jquery method for post:

<script type="text/javascript">

    function email(){
        var myTextField = document.getElementById('email_hidden').value;
        //alert(myTextField);
        $.post("sendmail.php", {"email_user": myTextField}, function(data) {
            alert(data);
        });
    }

</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM