user2896120
user2896120

Reputation: 3282

Returning string to Ajax from PHP

I have an Ajax script that relays form information to PHP upon user submission. The data is inserted into the table and then returns a string back to Ajax. For some reason, instead of getting the string I am getting the full HTML code of the page. How do I go about getting the string instead of the HTML code?

HTML

  <form id='orderForm' action='' method='post'>

                        <h2>Choose your pizza size</h2><hr>
                            <select name='size'>
                            <option value='' disabled selected>Choose a size</option>
                            <option value='small'>Small</option>
                            <option value='medium'>Medium</option>
                            <option value='large'>Large</option></select>

                            <h2>Choose your toppings</h2><hr><label><input type='checkbox' name='check_list[]' value='beef'>Beef</label>
                            <label><input type='checkbox' name='check_list[]' value='pepperoni'>Pepperoni</label>
                            <label><input type='checkbox' name='check_list[]' value='chicken'>Chicken</label>
                            <label><input type='checkbox' name='check_list[]' value='sausage'>Sausage</label>


                 <h2>Enter your details</h2><hr><input type='text' name='name' placeholder='Full Name'>
                        <input type='email' name='email' placeholder='Email'>
                        <input type='text' name='phone' placeholder='Phone number'>


                    <input type='text' name='address' placeholder='Address'>
                        <input id='zip' type='text' name='zip' placeholder='Zip Code'>
                        <p id='message'></p>



                      <input id='submitBtn' type='submit' name='submitBtn' value='Place Order'>
                        </form>

AJAX

$.ajax({
             type: 'post',
             url: 'validation.php',
             data: $("#orderForm").serialize(),
             datatype: "html",
             success: function(data){
                  window.location = data;
             }
       })

PHP

if (isset($_POST["email"])){

$orderId = time() + mt_rand(1,10);

$toppings = implode(', ', $_POST['check_list']);
$result = $db->prepare("INSERT INTO orders (order_id, type, pizza_type, size, toppings, name, address, email, number) VALUES (?, ?,?,?,?,?,?,?,?)");

$result->bind_param("sssssssss", $orderId, $_GET['type'], $_GET['order'], $_POST['size'], $toppings, $_POST['name'], $_POST['address'], $_POST['email'], $_POST['phone']);

$result->execute();
$db->close();

echo "?success=true&orderid=' . $orderId . '&toppings=' . $toppings";
}

Upvotes: 0

Views: 1378

Answers (2)

user7941334
user7941334

Reputation:

In js I recommend you to use:

ajax.done()
ajax.fail()
ajax.always()

Notice the use of:

'method'
'dataType'

So, in Js would be like:

var ajax = $.ajax({
            method: 'POST',
            dataType: 'json',
            url: 'validation.php',
            data: $("#orderForm").serialize()
        });

        ajax.done(function (data, textStatus, jqXHR) {
            window.location = data;
        });

And in PHP:

echo json_encode('your string');

EDIT:

I can't comment cause I'm new hier, so I'll attach my new ideas hier. I just tested again in-depth.

Test 1:

I've assigned dataType: 'json' and data: $("#testForm").serialize() in js. I submitted. In php I checked received values. All ok! I echo'ed an uri string using json_encode($uri). I received the uri string in js and applied window.location = result. I was successfully redirected!

Test 2

I've assigned dataType: 'html' in js. I submitted. In php I checked received values. All ok! I echo'ed an uri string using echo $uri. I received the uri string in js and applied window.location = result. I was successfully redirected!

Proposals:

So, all works here. But, user2896120, I suspect something. So:

  • Your bind_param has "sssssssss" as first argument. BUT at least the $orderId is integer. Change to something like

    $result->bind_param("dsss...", $orderId, /.../);

  • close the connection before echo'ing your resulting string.

  • don't print anything before echoing your resulting string. No echo, print_r, var_dump, etc.

  • If you receive html code as result, READ IT! Is it REALLY your page html code? Or some other html code from an "early" printing (e.g before echo'ing your resulting string)?

New idea:

If you receive the html code of your page, then check to see if you find also your resulting string "?success=true&orderid=..." at the end of the returned html page code.

Another idea:

Obs. apropos 'hidden':

<input type="text" name="order" hidden value="<?php echo $_GET['order']; ?>>

should be defined like this

<input type="hidden" name="order" value="<?php echo $_GET['order']; ?>>

Obs. apropos 'type':

Don't use 'type' as value in 'name' attribute. Maybe it is seen as a reserved name! Both at client and db part. And it seems that your data inserting exactly at 'type' value breaks.

So, I mean change 'type' hier (change to 'mytype' maybe, for testing):

<input name="type" hidden value="<?php echo $_GET['type']; ?>"

Upvotes: 0

Junius L
Junius L

Reputation: 16122

Hi I don't how you get $_GET['type'] and $_GET['order']

if (isset($_POST["email"])){

    $orderId = time() + mt_rand(1,10);

    $toppings = trim(implode(',', $_POST['check_list']));
    $type = $_POST['type'];
    $order = $_POST['order'];
    $result = $db->prepare("INSERT INTO orders (order_id, type, pizza_type, size, toppings, name, address, email, number) VALUES (?, ?,?,?,?,?,?,?,?)");

    $result->bind_param("issssssss", $orderId, $type, $order, $_POST['size'], $toppings, $_POST['name'], $_POST['address'], $_POST['email'], $_POST['phone']);
    try {
        $result->execute();
    }catch (Exception $e) {
        echo $e->getMessage();
    }
    $db->close();
    echo "?success=true&orderid=" . $orderId . "&toppings=" . $toppings;
}

form page

<head>
    <link href='index.css?<?php echo time(); ?>' rel='stylesheet' type='text/css'>
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class='container'>
    <div class='startContainer'>
        <?php
        if (!isset($_GET['type'])) {
            if (!isset($_GET['success'])) {
                echo "<img src='order_bg'>
                        <a href='?type=delivery'><div class='orderOptions'>
                            <i class='material-icons'>directions_car</i>                            
                            Delivery
                        </div></a>

                        <a href='?type=carryout'><div class='orderOptions'>
                            <i class='material-icons''>store</i>
                            Carry out
                        </div></a>
                    </div>";
            } else {
                echo "<h1>Success!</h1><p>Your order id is: " . $_GET['orderid'] . "</p><br>
                    <p>Toppings: " . $_GET['toppings'] . "</p>
                    <h1>Your pizza will be ready in:</h1>
                    <h2 id='counter' style='text-align: center'></h2>";
            }
        } else {
            if (!isset($_GET['order'])) {
                echo "<img src='make_pizza'> &nbsp<h2>Choose your pizza.</h1>
                    <a href='?type=$_GET[type]&order=custom'><div class='pizzaType'>
                        <img src='custom_pizza'>
                        <i class='material-icons'>apps</i>
                        Custom made
                    </div></a>
                    <a href='?type=$_GET[type]&order=grandma'><div class='pizzaType'>
                        <img src='grandma_pizza'>
                        <i class='material-icons'>local_pizza</i>
                        Grandma's Pizza
                    </div></a>";
            } else {
                echo "<img src='order_pizza'>

                    <form id='orderForm' action='' method='post'>";

                if ($_GET['order'] == 'custom') {
                    echo "<h2>Choose your pizza size</h2><hr>
                            <select name='size'>
                            <option value='' disabled selected>Choose a size</option>
                            <option value='small'>Small</option>
                            <option value='medium'>Medium</option>
                            <option value='large'>Large</option></select>

                            <h2>Choose your toppings</h2><hr><label><input type='checkbox' name='check_list[]' value='beef'>Beef</label>
                            <label><input type='checkbox' name='check_list[]' value='pepperoni'>Pepperoni</label>
                            <label><input type='checkbox' name='check_list[]' value='chicken'>Chicken</label>
                            <label><input type='checkbox' name='check_list[]' value='sausage'>Sausage</label>";
                }

                echo "<h2>Enter your details</h2><hr><input type='text' name='name' placeholder='Full Name'>
                        <input type='email' name='email' placeholder='Email'>
                        <input type='text' name='phone' placeholder='Phone number'>
                        <input name='type' hidden value='" . $_GET['type'] . "' type='text'> 
<input type='text' name='order' hidden value='" . $_GET['order'] . "'>";

                if ($_GET['type'] == 'delivery') {
                    echo "<input type='text' name='address' placeholder='Address'>
                        <input id='zip' type='text' name='zip' placeholder='Zip Code'>
                        <p id='message'></p>";
                }


                echo "<input id='submitBtn' type='submit' name='submitBtn' value='Place Order'>
                        </form>";
            }
        }
        ?>
    </div>
</div>
<script>
    var count = 60,
        timer = setInterval(function () {
            $("#counter").html(count-- + " seconds");
            if (count == 0) {
                $("#counter").html("Order complete!");
                clearInterval(timer);
            }
        }, 1000);

    var zipCodes = ["30060", "30069", "30090", "30065", "30063", "30061", "30006", "30007", "30008", "30081", "30067", "30064", "30082", '30080', "30339", "30068", "30062", "30066", "30152", "30126", "30160", "30156", "30327", "30144", "30106", "30328", "30111", "30127", "30342"];

    $("#zip").on("focus", function () {
        $("#submitBtn").prop("disabled", false);
        $("#submitBtn").removeAttr("style");
        $("#message").text("");
    })

    $('#orderForm').submit(function (e) {
        e.preventDefault();
        e.stopImmediatePropagation();

        var zip = $("#zip").val();
        if (zipCodes.indexOf(zip) == -1) {
            $("#submitBtn").prop("disabled", true);
            $("#submitBtn").css("background-color", "gray");
            $("#message").text("We're sorry, but we do not deliver to the following zip code.");
        }
        else {
            $.ajax({
                type: 'post',
                url: 'file.php', // change this to php file.
                dataType: "text",
                data: $("#orderForm").serialize(),
                success: function (data) {
                   window.location = data;
                }
            })
        }
    })

</script>
</body>

Upvotes: 1

Related Questions