开发者

How to get the values from a $.ajax using php

I'm trying to use $.ajax to send some values to a php page which then sends an email, I can't figure out how to get the values from $.ajax in my php file,

any help would be appreciated,

$(function() {

$('form#email input[type=image]').click(function() {

    var name = $('form#ema开发者_运维技巧il #name').val();
    var enq = $('form#email #enq').val();
    var dataString = 'name=' + name + '&enq=' + enq;

    $.ajax({
        type:'POST',
        url:'email.php',
        data:dataString,
        success:function() {
            $('form#email').fadeOut();
        }

    });
    $('form#email')[0].reset();
    return false;                              
 });
});

php file

if (isset($_POST['submit_x'])) {

$name = $_POST['name'];
$enq = $_POST['enq'];
$name = htmlentities($name);
$enq = htmlentities($enq);

//echo $name,$enq;

$to = 'amirkarimian@hotmail.co.uk';
//$to = 'tutor@inspiretuition.co.uk'
$subject = 'Enquiry';
$message = $enq;

mail($to,$subject,$message);

if(!mail) {
    echo 'failed to send mail';
}
}

the email doesn't get sent. if I dont use $.ajax and submit the form normally the email get sent.

thanks


You're checking for a variable you're not submitting, submit_x, you'll need to remove that outer if check. Also, it's better to let jQuery serialize your strings properly (what if there's a & in there?) like this:

$(function() {
  $('#email input[type=image]').click(function() {
    $.ajax({
        type:'POST',
        url:'email.php',
        data: { name: $('#name').val(), enq: $('#enq').val() }
        success:function() {
            $('form#email').fadeOut();
        }
    });
    $('#email')[0].reset();
    return false;                              
  });
});

Or if the <form> elements have proper name attributes (they should, for graceful degradation) , you can replace data: { name: $('#name').val(), enq: $('#enq').val() }
with data: $('#email').serialize().


try sending 'submit_x' to php :)


You can use a data map to define your data:

var name = $('form#email #name').val();
   var enq = $('form#email #enq').val();

   $.ajax({
    type: 'POST',
    url: 'email.php',
    dataType: 'html',
    data: {
     submit_x   : 1,
     name     : name,
     enq     : enq
   },
   success: function(html){
    $('form#email').fadeOut();
   },
   error:  function(e, xhr)  { alert('__a Error: e: ' + e + ', xhr:' + xhr); }
  });
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜