2017-07-08 43 views
0

我試圖發送使用JSON和AJAX數據數組的PHP表單郵件,但由於某些原因,該郵件沒有發送數據... (我測試了傑森串並驗證它,以確保它包含數據)發送AJAX JSON數組電子郵件與PHP郵件

這裏是我的代碼有:

JSON:

function submitFields() { 
    form_elements = []; 
    $('.dataField').each(function() { 
     frm_name = $(this).attr('name'); 
     frm_qty = $(this).val(); 
     frm_price = $(this).data('price'); 
     current_frm_obj = {name:frm_name, qty:frm_qty, price:frm_price}; 
     form_elements.push(current_frm_obj); 
    }); 

    $.ajax({ 
     type: "POST", 
     url: "mailer.php", 
     data: { result:JSON.stringify(form_elements) }, 
     success : function(response) { 
      console.log(form_elements); 
      alert(response); 
     }  
    }); 
} 

PHP郵件:

$data = $_POST["result"]; 
$decoded = json_decode($data); 
$errors = ''; 
$myemail = '[email protected]'; 

$to = $myemail; 
$email_subject = "Form info"; 
$email_body = 
$decoded = json_decode($data); 
foreach ($decoded as $curr_element) { 
    $fieldName = $curr_element->name; 
    $fieldQty = $curr_element->qty; 
    $fieldPrice = $curr_element->price; 

    if ($fieldQty != 0) { 
     $fieldName .': <br />' . $fieldQty; 
     if ($fieldPrice != 0) { 
      'Qty: ' . $fieldQty . '<br />'; 
      'Price: ' . $fieldPrice . '<br />'; 
      'Total: ' . ($fieldPrice*$fieldQty) . '<br /><br />'; 
      } 
    } 
} 

$headers = "From: studiodeshe <[email protected]> \n"; 
$headers .= 'Content-type: text/html; charset=utf-8'; 

mail($to,$email_subject,$email_body,$headers); 
header('Location: ty.html'); 

我猜測,我試圖解碼郵件中的數據的方式存在一些問題,但無法找到解決方案...

回答

0

好的我解決了它。如果有人將需要在未來解決方案那就是:

從JSON數據應在開始進行解析,並保存成變種,像這樣:

$data = $_POST["result"]; 
$decoded = json_decode($data); 
$mailData = ""; 
foreach ($decoded as $curr_element) { 
    $fieldName = $curr_element->name; 
    $fieldQty = $curr_element->qty; 
    $fieldPrice = $curr_element->price; 
    if ($fieldQty != 0) { 
     if ($fieldPrice != 0) { 
      $input = $fieldName .': <br /> 
      Qty: ' .$fieldQty. '<br /> 
      Price: ' . $fieldPrice . '<br /> 
      Total: ' . ($fieldPrice*$fieldQty) . 
      '<br /><br />'; 
      $mailData .= $input; 
      } 
    } 


} 


$errors = ''; 
$myemail = '[email protected]';//<-----Put Your email address here. 

$to = $myemail; 
$email_subject = "Configurator Lead"; 
$email_body = $mailData; 

$headers = "From: studiodeshe <[email protected]> \n"; 
$headers .= 'Content-type: text/html; charset=utf-8'; 

mail($to,$email_subject,$email_body,$headers);