A
A
Artem2018-02-09 17:09:21
PHP
Artem, 2018-02-09 17:09:21

How to pass an array to PHP via AJAX and send it to email?

There is this code where I create an array and try to transfer it using AJAX to a PHP file, and then send it to myself by email.
Here is the HTML:

<select id="id">
  <option>Раз</option>
  <option>Два</option>
  <option>Три</option>
</select>

<select id="super">
  <option>Четыре</option>
  <option>Пять</option>
  <option>Шесть</option>
</select>

<select id="puper">
  <option>Семь</option>
  <option>Восемь</option>
  <option>Девять</option>
</select>

<form>
<input type="text" name="name" placeholder="Как к вам обращаться">
<input type="email" name="email" placeholder="Ваш email">
<input type="submit" id="btn" value="Отправить">
</form>


Here is the JS:
var idFin = $("#id option:selected").text();
var superFin = $("#super option:selected").text();
var puperFin = $("#puper option:selected").text();
var allData = {
    id: idFin,
    super: superFin,
    puper: puperFin,
    name: "",
    email: "",
};
var test = [];

$('#btn').click(function () {
  if ($("input[type='email']").val() == "") {
    $("input[type='email']").css("color","red");
    return false;
  };
});    

$("form").submit(function () {
  allData[name] = $("input[type='text']").val();
  allData[email] = $("input[type='email']").val();
  test.push(allData);
  $.ajax({
    type: "POST",
    url: "mail.php",
    data: {test: test},
    dataType: "json",
    success: function () {
      alert("Все супер!");
    },
    error: function(){
      console.log('error');
    }
  });
  return false;
});


And here is the php, which is supposed to send me a message:
<?php

$recepient = "[email protected]";

$id= trim($_POST["id"]);
$super = trim($_POST["super"]);
$puper = trim($_POST["puper"]);
$name = trim($_POST["name"]);
$email = trim($_POST["email"]);
$message = "Id: $id \nSuper: $super \nPuper: $puper \nИмя: $name \nE-mail: $email";

$pagetitle = "Новое сообщение";

mail($recepient, $pagetitle, $message, "Content-type: text/plain; charset=\"utf-8\"\n From: $recepient");
?>

But for some reason nothing comes out, the page is reloaded when the form is submitted, no errors are visible in the console and the message does not arrive accordingly. Where did I make a mistake? Tell me please!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tyzberd, 2018-02-09
@thegreatestmafaka

Why create it on click

$('#btn').click(function () {
  allData = {
    id: idFin,
    super: superFin,
    puper: puperFin,
    name: "",
    email: "",
  }
});

quotes are needed here or so allData.name allData["name"]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question