Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$jsonObj data not being passed via ajax and POST on IE(11) only

I'm trying to pass data via post with ajax to my sendjs.php.

jsonObj is not being passed in IE11 only (havent tested lower versions of IE but it works in Edge and all other browsers). FormData and captchaResponse are being passed though.

In 'Network' in IE 11 inspector the post data is:

cart: [null] and there are no errors displayed in console.

All other browsers it contains the data:

eg. cart: {name: "130 Litre Polypropylene Soakwells", price: "$39.95", quantity: "4", total: "$159.80"},…]

Live site here: www.diysoakwells.com.au (you can add an item and checkout to test).

Have spent ages trying to find the cause and now I'm not even sure where to go from here to be honest, so any information would be appreciated and I will update the post with any info as requested.

app.js

$(function() {


    // Get the form.
    var form = $("#ajax-contact");

    // Get the messages div.
    var formMessages = $("#form-messages");

    var spinner = $("#spinner");

    var submit = $("#submit");

    // Set up an event listener for the contact form.
    $(form).submit(function(e) {
        // Stop the browser from submitting the form.
        e.preventDefault();

        //display the cog animation
        $(spinner).removeClass("hidden");
        //hide the submit button
        $(submit).addClass("hidden");



        var jsonObj=[];
        for(i=1;i<$(".item-price").length;i++)
        {
            var items={};
            var itemname = $(".item-name").get(i);
            var itemprice = $(".item-price").get(i);
            var itemquantity = $(".item-quantity").get(i);
            var itemtotal = $(".item-total").get(i);
            items["name"] = itemname.innerHTML;
            items["price"] = itemprice.innerHTML;
            items["quantity"] = itemquantity.innerHTML;
            items["total"] = itemtotal.innerHTML;
            jsonObj.push(items);

        }

        console.log(jsonObj );

        var formdata = {};
        formdata["textbox"] = $("#textbox").val();
        formdata["name"] = $("#name").val();
        formdata["phone"] = $("#phone").val();
        formdata["email"] = $("#email").val();
        formdata["address"] = $("#address").val();
        formdata["grandtotal"] = simpleCart.grandTotal();

        var x = 
        {
            "cart" : jsonObj,
            "formdata" : formdata,
            "captchaResponse" : $("#g-recaptcha-response").val()
        };
        //jsonString = jsonObj+formdata;
        var y = JSON.stringify(x);
        console.log(y);
        var result = jQuery.parseJSON(y);
        console.log(result);


        // Serialize the form data.
        //var formData = $(form).serialize();

        // Submit the form using AJAX.
        $.ajax({
            type: "post",
            url: "sendjs.php" ,
            //url: $(form).attr("action"),
            data: y,
            contentType: "application/json; charset=utf-8",
            processData: false,
            success: function (response) {
                        if(response=="Thank You. Your order has been sent and a copy mailed to your inbox.")
                        {
                    //remove the button animation
                    $(spinner).addClass("hidden");
                    $(formMessages).removeClass("error");
                    $(formMessages).addClass("success");
                    $("#textbox").val("");
                    $("#name").val("");
                    $("#email").val("");
                    $("#message").val("");
                    $("#phone").val("");
                    $("#address").val("");

                        }
                        else
                        {
                    $(formMessages).removeClass("success");
                    $(formMessages).addClass("error");
                    $(spinner).addClass("hidden");
                    $(submit).removeClass("hidden");
                        }

                $(formMessages).text(response);

            }
        });
    });

});

sendjs.php

<?php
//Debugging
//ini_set( 'display_errors', 1 );
//error_reporting( E_ALL );

//replaces file_get_contents due to restrictions on server
function get_data($url)
    {
      $ch = curl_init();
      $timeout = 5;
      curl_setopt($ch,CURLOPT_URL,$url);
      curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
      curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
      $data = curl_exec($ch);
      curl_close($ch);
      return $data;
    }

    //turn url_fopen on due to restrictions on server
    //ini_set('allow_url_fopen', true);

    date_default_timezone_set('Australia/Perth');
    $time = date ("h:i A"); 
    $date = date ("l, F jS, Y");
    $json = file_get_contents('php://input');
    $obj = json_decode($json,true);
    $captcha = $obj["captchaResponse"];
    $captcha;
    $secretKey = "scrubbed";
    $ip = $_SERVER['REMOTE_ADDR'];
    $response = get_data("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);

    //not used due to server restictions
    //$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);

    $responseKeys = json_decode($response,true);

    if(intval($responseKeys["success"]) !== 1) {
        echo "Please Click on the Captcha";
        return false;
    }
    else 
    {
    //echo $items;
    $name = $obj["formdata"]["name"];
    $phone = $obj["formdata"]["phone"];
    $email = $obj["formdata"]["email"];
    $textbox = $obj["formdata"]["textbox"];
    $address = $obj["formdata"]["address"];
    $grandtotal  = $obj["formdata"]["grandtotal"];
    $text = "<html style='font-family:arial'>
    <body>
        <h1 style='color:crimson;'>DIY Soakwells</h1>
        <p>This order was submitted from www.diysoakwells.com.au on $date at $time</p>
        <p>$name thank you for your order inquiry. Deliveries are normally every Friday, we will be in contact shortly to discuss your order and confirm a time.</p>
        <p>An invoice will be issued after delivery for payment via bank transfer.</p>
        <p>In the meantime if you haven't already seen it, you can take a look at www.soakwellcalculator.com.au to confirm the number of soakwells you ordered will be adequate.</p>
        <br>

        <h2 style='color:crimson;'>CUSTOMER DETAILS</h2>
        <p><b>Email:</b>\n$email</p>
        <p><b>Name:</b>\n$name</p>
        <p><b>Phone:</b>\n$phone</p>
        <p><b>Delivery Address:</b>\n$address</p>
        <p><b>Message:</b>\n$textbox</p>
        <br>

        <h2 style='color:crimson;'>ORDER DETAILS</h2>";

        $items_in_cart = count($obj["cart"]);
        for($i=0; $i < $items_in_cart; $i++) {
            $iname = $obj["cart"][$i]["name"];
            $price = $obj["cart"][$i]["price"]; 
            $quantity = $obj["cart"][$i]["quantity"];
            $total = $obj["cart"][$i]["total"];
            //display looped cart data      
            $items .= "<p>$iname x $quantity - $price <small>ea.</small> <b>Sub Total: </b> $total .</p>";
        }

        $final_total ="<br>
        <p><b>Total: </b>$$grandtotal <small>inc. GST</small></p>
        </body>
        </html>";

        //Email Content
        $body = $text.$items.$final_total;

        // Set the email subject.
        $subject = "New order from $name";

        // Build the email content.
        $email_content = $body;

        // Build the email headers.
        $email_headers = 'MIME-Version: 1.0' . PHP_EOL;
        $email_headers .= 'Content-Type: text/html; charset=ISO-8859-1' . PHP_EOL;
        //$email_headers .= 'To:' . $name . '<' . $email . '>' . PHP_EOL;
        $email_headers .= 'From: DIY Soakwells <[email protected]>' . PHP_EOL;
        $email_headers .= 'CC: [email protected]' . PHP_EOL;
        $email_headers .= 'Reply-To: DIY Soakwells <[email protected]>' . PHP_EOL;
        $email_headers .= 'Return-Path: DIY Soakwells <[email protected]>' . PHP_EOL;
        $email_headers .= 'X-Sender: DIY Soakwells <[email protected]' . PHP_EOL;
        $email_headers .= 'X-Mailer: PHP/' . phpversion() . PHP_EOL;
        //$email_headers .= 'X-Priority: 1' . PHP_EOL;



        //validate Email
        $email_check = filter_input(INPUT_POST, $email, FILTER_VALIDATE_EMAIL);
        //Recipients
        $to = $email;

        if (mail($to, $subject, $email_content, $email_headers, '[email protected]')) {
            // Set a 200 (okay) response code.
            //http_response_code(200);
            echo "Thank You. Your order has been sent and a copy mailed to your inbox.";
        } else {
            // Set a 500 (internal server error) response code.
            //http_response_code(500);
            echo "There appears to be an issue with our server, please ring 0420 903 950 or email [email protected].";
        }      
    }       
?>

Hope someone can give me some tips.

Edit: Added cart modal html

<!-- cart modal panel -->               
<section class="modal fade cartModal" role="dialog" tabindex="-1">

<div class="modal-dialog" role="document">
<div class="modal-content">

<!-- Modal Header-->                
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>

        <h3 class="modal-title cart_summary">
            <b>Cart Summary</b>
        </h3>       
    </div>

<!-- Cart Modal Body -->
<section class="modal-body">
        <div class="checkout">

            <!-- Cart Items -->
            <div class="simpleCart_items"></div>

                    <!-- Cart Items Footer -->
                <div class="panel-footer">
                <div class="row">
                    <div class="col-xs-12 col-sm-4 cart_modal_btn">
                        <a class="btn btn-default btn-sm" onclick="simpleCart.empty();">Clear Cart</a>
                    </div>
                    <div class="col-xs-12 col-sm-8 cart_footer_text">
                        <span class="total">Current Total: &nbsp;
                        <b class="simpleCart_grandTotal"></b>   
                        <small class=gst>Inc. GST</small>
                        </span>
                    </div>
                </div>
            </div>
        </div>

        <div>
            <h3 class="cart_summary">           
                <b>Checkout</b>
            </h3>
        </div>

<!-- Customer Details Form -->
    <section class="details_form">
        <b class="invoice_info">Due to the custom nature of this service we do not take payment until your order is confirmed and the materials are delivered.</b>

        <b class="invoice_info">You will be emailed an invoice with our account details. Payment terms are 5 days from the invoice date please.</b>

        <p class="invoice_info">For payment we accept bank transfer and VISA / Master Card <small>(2.3% surcharge for credit cards).</small></p>

        <form id="ajax-contact" class="contact_form" method="post"> 
            <fieldset>                  
                <h4 class="contact_form_title">Questions / Additional Information</h4>

                <div class="textbox_container">
                    <textarea rows="5" style="overflow-y:hidden" class="textbox" name="textbox" id="textbox"></textarea>
                </div>

                <h4 class="contact_form_title">Customer Details</h4>    

                <table>
                    <tr>
                        <th><label for="name" class="cart_label">Enter Name</label></th>
                        <td><input type="text" name="name" placeholder="Name Required" class="input" id="name" required /></td>
                    </tr>
                    <tr>
                        <th><label for="phone" class="cart_label">Enter Phone Number</label></th>
                        <td><input type="tel" placeholder="Phone Number Required" name="phone" class="input" id="phone" required/></td>             
                    </tr>
                    <tr>
                        <th><label for="emaile" class="cart_label">Enter Email</label></th>
                        <td><input type="email" placeholder="Email Required" name="emaile" class="input" id="emaile" required/></td>
                    </tr>
                    <tr>                            
                        <th><label for="address" class="cart_label">Enter Address</label></th>
                        <td><input type="text" name="address" placeholder="Address / Suburb" class="input" id="address" required/></td>
                    </tr>
                </table>
            </fieldset>

                <!-- captcha -->
            <div class="captcha_container">
                <div class="g-recaptcha" data-sitekey="6LfPjyMTAAAAANe_qucSV5ZFAuDNO4Ud524-NGoa" data-size="compact"></div>
            </div>


            <section class="fb_container">
                <div class="fb-like" data-href="http://www.facebook.com/DiySoakwells" data-layout="button_count" data-width="225" data-action="like" data-show-faces="false" data-share="true"></div>
            </section>
            <br/><!-- css this -->



            <fieldset class="submit">

                <div class="formMessages submit_field"></div>

                <div id="spinner" class="hidden success submit_field"><i class="loader2"></i></div>

                <input id="submit" type="submit" name="Submit" value="Send" style="cursor:pointer" class="success"/>
            </fieldset>

        </form>
    </section>
</section>      


<!-- Modal Footer-->
<section class="modal-footer">
        <button type="button" class="btn btn-default close" aria-label="Close" data-dismiss="modal">Back to Shop</button>
</section>

</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

</section><!-- /.main section -->

Simple Cart config

simpleCart({
//Setting the Cart Columns for the sidebar cart display.
cartColumns: [
//{ attr: "image", label: false, view: "image"},
//Name of the item
{ attr: "name" , label: "Item" },
//Quantity displayed as an input
{ attr: "quantity", label: "Qty", view: "input"},



    //Price of item
    //{ attr: "price", label: "Price", view: "currency"},
    //Subtotal of that row (quantity of that item * the price)
    { attr: "total" , label: "SubTot", view: "currency"  }
],
cartStyle: "table" ,
checkout: {
type: "SendForm" ,
url: "/php/sendjs.php" ,
method: "POST" ,




}

});

simpleCart.bind( 'beforeCheckout' , function( data ){
data.name = document.getElementById("name").value;
data.textbox = document.getElementById("textbox").value;
data.emaile = document.getElementById("emaile").value;
data.phone = document.getElementById("phone").value;
data.address = document.getElementById("address").value;
});

Codepen link to simplecart.js

Copy of simplecart.js

like image 948
JPB Avatar asked Sep 01 '17 02:09

JPB


People also ask

How do I send data to a server using Ajax?

The POST method transports data in the request body. Data can be transported in JSON and XML formats. You can use the XMLHttpRequest object (XHR) to communicate with a web server using the AJAX technique. This is the classic way to do AJAX, but it's not the best way now that the Fetch API is supported in modern browsers.

Why won’t my Ajax calls work with Internet Explorer?

When you do the same with Internet Explorer you’ll notice something strange happen, or rather, not happening. The requests are not being made at all, they are being totally ignored by Internet Explorer. What is happening is that you’re likely making a GET request to a web service for your AJAX call.

How to execute an Ajax request using jQuery?

We can also execute an AJAX request using a library like jQuery. POST requests in jQuery are executed using the post () function. I'll show you how to use jQuery to execute an AJAX request, but honestly with the new JavaScript Fetch API, there's really no need to import a whole library like jQuery just for AJAX.

Does Internet Explorer cache Ajax requests?

Internet Explorer, in its wisdom, will automatically cache responses from GET requests while other browsers will let you decide if you’d like to cache the result or not. Once IE has successfully made a GET request, it will no longer even make that AJAX call until the cache expires on that object.


1 Answers

UPDATE 2

Your code here uses items, not item, and that works fine for me. I checked your live site, which uses item, and found that code does not work, it exhibits the problem you describe. I copied that live, broken code locally and was able to fix the problem as described below.

UPDATE

I stumbled on the solution (described below), without understanding it. After more research, I've now found the cause of the problem: item is defined as a native function in IE.

  • Related question 1
  • Related Question 2
  • Related Question 3

How I stumbled onto the answer

I copied your code locally and played around with it. I noticed jsonObj was created OK, though the contents looked strange. Likewise x was created OK, but after JSON.stringify your cart contents were lost.

console.dir(jsonObj) showed that it was an array of objects, but each object showed up as a function called item - in IE11 only:

enter image description here

In Chrome it is an array of plain objects.

The name of that function (item) seems strange, considering it is the name of the object you are storing your cart items in. And JSON.stringify on a function will return null - so that could explain it.

Checking your code again I notice you did not declare item anywhere. I tried just adding:

var item;

outside your for (i=1...) loop, and this solved it for me! Cart contents are not lost by JSON.stringify, and devtools shows the cart and your other data is POSTed successfully.

Maybe item declared somewhere else (in SimpleCart?) as a function, and that's getting in the way? UPDATE Yes this is exactly what is happening, though it is declared by the browser itself, not in any JS.

like image 85
Don't Panic Avatar answered Nov 07 '22 20:11

Don't Panic