0

I am making a small webbshop that uses localstorage for items that are put in a cart. When I go to the purchase site to send the information I use jQuery to get the localstorage and send it to my php script. This works fine, but I either sent two emails(one empty and one with localstorage) or I only send the localstorage.

New to js/jquery and php so I think the problem is that the information doesn't get sent to the jQuery script properly and then on to the php script.

I tried sending the form as this:

  var values = $(this).serialize();

And then add it after orderDetails in my post but I didn't get much from that.

This is my code now:

HTML:

<div class="form-container">
    <form action="sendOrderInfo.php" method="post" id="order">
        <h1 id="formh1">Dina uppgifter</h1>
        <fieldset>
        <legend>
            <strong>Namn och kontaktinformation</strong>
        </legend>
        <div class="account-details">
            <div><label>Förnamn*</label><input type="text" name="fname" id="fname" placeholder=" " required></div>
            <div><label>Mejl*</label><input type="text" name="email" id="email" placeholder=" " required></div>
            <div><label>Efternamn*</label><input type="text" name="lname" id="lname" placeholder=" " required></div>
            <div><label>Telefon*</label><input type="number" name="tel" id="tel" placeholder=" " required></div>
        </div>
    </fieldset>
    <fieldset>
        <legend>
            <strong>Ort och adress</strong>
        </legend>
        <div class="personal-details">
            <div>
                <div><label>Gatuadress*</label><input type="text" name="adress" id="adress" placeholder=" " required></div>
                <div><label>Postkod*</label><input type="number" name="zip" id="zip" placeholder=" " required></div>
                <div><label>Ort*</label><input type="text" name="ort" id="ort" placeholder=" " required></div>
            </div>
            <div>
                <div>
                    <label>Faktureringstyp*</label>
                    <div class="mailType">
                        <input type="radio" id="st_mail" name="sendtype" value="via mail" checked="checked">
                        <label for="via mail">Mejl - 0 kr</label><br />
                        <input type="radio" id="st_post" name="sendtype" value="via brev">
                        <label for="via post">Post - 15 kr</label><br />
                    </div>
                </div>
                <div><label>Rabattkod</label><input type="text" name="rabatt" placeholder=" "></div>
            </div>
        </div>
    </fieldset>
        <fieldset> <button name="submit" type="submit" value="submit" class="btn btn-purchase" id="submitOrder">Skicka</button></fieldset>
    </form>
</div>

jQuery:

$(document).ready(function () {
var orderDetails = localStorage.getItem('cartItems');
var orderTotal = localStorage.getItem('totalCost');

  $("#order").submit(function (event) {
    event.preventDefault();
    $.post("sendOrderInfo.php", {
      //Attatch storageinfo to post
      orderDetails: orderDetails,
      orderTotal: orderTotal,
      },
      function (data) {}).fail(function () {
        alert("Ursäkta, någonting gick fel hos oss. Försöka gärna igen.");
        localStorage.clear()
      });
    })
    $("#submitOrder").click(function () {
        window.location.replace("orderdone.html");
    })
})

PHP:

#Adress and contact
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$tel = $_POST['tel'];
$gata = $_POST['adress'];
$zip = $_POST['zip'];
$ort = $_POST['ort'];
$visitor_email = $_POST['email'];
$faktura = $_POST['sendtype'];
$rabattkod = $_POST['rabatt'];
#Order Info
$orderInfo = $_POST['orderDetails'];
$orderTotal = $_POST['orderTotal'];
$orderedItems = (array)json_decode($orderInfo, true);
$total = json_decode($orderTotal);
$email_from = 'testmail@cookiesndragons.se';
$email_subject = "New OrderType";
$email_body = "Avsändare: $fname, $lname.\n".
        "Adress: $gata $zip $ort \n".
        "Email: $visitor_email \n".
        "Telefon nummer: $tel \n\n".
        "Fakturasätt: $faktura \n\n\n\n".
        "Order:  \n";
        foreach ($orderedItems as $key){
         $email_body .= "Vara: " . $key['name'] . "
         Pris: " . $key['price'] . "
         Antal: " . $key['inCart'] . "\n\n";
        }
        $email_body .=
        "\n".
        "OrderTotal: $total \n\n".
                "Inputs: " . $v;


$to = "testmail@cookiesndragons.se";//<== update the email address
$headers = 'Content-Type: text/plain; charset=utf-8' . "\r\n";
$headers .= 'Content-Transfer-Encoding: base64' . "\r\n";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,utf8_decode($email_subject),utf8_decode($email_body),utf8_decode($headers));

//done. redirect to thank-you page.
header('Location: orderdone.html');

The post $(this).serialize() -- How to add a value? helped me get the right information sent to the mail. But I still get 3 mails sent every time I send the information. I changed jQuery to this:

$(document).ready(function () {
    var orderDetails = localStorage.getItem('cartItems');
    var orderTotal = localStorage.getItem('totalCost');



  $("#order").submit(function (event) {
    event.preventDefault();
    var data = $(this).serializeArray(); // convert form to array
    data.push({name: "orderDetails", value: orderDetails});
    data.push({name: "orderTotal", value: orderTotal});
    $.ajax({
        type: 'POST',
        url: this.action,
        data: $.param(data),
    });
    })
    $("#submitOrder").click(function () {
        window.location.replace("sendOrderInfo.php");
    })
})
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
KarateRai
  • 1
  • 1
  • Any errors in your browser console? `.serielize()` should be `.serialize()` – brombeer Oct 11 '21 at 06:41
  • No errors from what I can see. – KarateRai Oct 11 '21 at 06:45
  • Your jQuery post only sends `orderDetails` and `orderTotal`, it doesn't send the rest of the inputs in the form though? – M. Eriksson Oct 11 '21 at 06:49
  • Yeah, this is what I assumed was the problem.. But I'm not sure how to make that work.. I tied doing this: var formData = $(this).serialize(); and then add it with orderDetails. But I can't get the format right in php.. Used `$formData = $_POST['formData']; $formInfo = (array)json_decode($formData, true)` Also tried without true and without array.. – KarateRai Oct 11 '21 at 06:55
  • Since you said new to jquery and php: stuff like this is usually done using php sessions. Maybe there is already an existing solution for you out there. – Alex Oct 11 '21 at 07:48
  • _Side note:_ Never use discounts and prices you get from the client. Anyone can change those values to be anything. – M. Eriksson Oct 11 '21 at 08:05
  • Does this answer your question? [$(this).serialize() -- How to add a value?](https://stackoverflow.com/questions/6539502/this-serialize-how-to-add-a-value) - It shows how you can add additional data to a serialized form. – M. Eriksson Oct 11 '21 at 08:06
  • We are aware of the fact that this is not the best way to go about this and that prices can be changed. I will spend more time and make this into something that works with a database in the future. But this will have to do for now untill I have some more experience. I'll check the link you posted asap. – KarateRai Oct 11 '21 at 08:17
  • i strongly suggest you take a look at a simple php framework that does this for you. securely. laravel is extremely easy and powerful. – Alex Oct 11 '21 at 09:11

0 Answers0