0

So I want to pass my JS array to my PHP code with AJAX, and I am facing a problem. My problem is the following: When I send my array to the php, it gives me the following error:

Notice: Undefined index: foods_added in C:\xampp\htdocs\etterem\order-food.php on line 2

My codes are the following:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rendelés felvétele</title>
<style type="text/css">
    body{
        font-family: Arail, sans-serif;
    }
    .search-box{
        width: 300px;
        position: relative;
        display: inline-block;
        font-size: 14px;
    }
    .search-box input[type="text"]{
        height: 32px;
        padding: 5px 10px;
        border: 1px solid #CCCCCC;
        font-size: 14px;
    }
    .result{
        position: absolute;        
        z-index: 999;
        top: 100%;
        left: 0;
    }
    .search-box input[type="text"], .result{
        width: 100%;
        box-sizing: border-box;
    }
    .result p{
        margin: 0;
        padding: 7px 10px;
        border: 1px solid #CCCCCC;
        border-top: none;
        cursor: pointer;
    }
    .result p:hover{
        background: #f2f2f2;
    }
    .list {
        padding-top: 20px;
    }
    .result {
        background-color: white;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
// var fields = 1;
// function add_fields() {
//     fields++;
//     var objTo = document.querySelector('.search-box')
//     var divtest = document.createElement("div");
//     divtest.innerHTML = '<input type="text" autocomplete="off" placeholder="Étel keresése"/><div class="result"></div>';

//     objTo.appendChild(divtest)
// }

var foods_added = [];
function add_food() {
    var food_name = document.getElementById('food_name').value;
    var entry = document.createElement('li');
    entry.appendChild(document.createTextNode(food_name));
    list.appendChild(entry);
    foods_added.push(food_name);
    document.getElementById('food_name').value = "";
}

function submit_list() {
    $.ajax({
        url: "order-food.php",
        method: "post",
        data: { foods_added : JSON.stringify(foods_added) },
        success: function(res) {
            console.log(res);
        }
    })
    window.location.href = "order-food.php";
}
$(document).ready(function(){
    $('.search-box input[type="text"]').on("keyup input", function(){
        var inputVal = $(this).val();
        var resultDropdown = $(this).siblings(".result");
        if(inputVal.length){
            $.get("backend-search.php", {term: inputVal}).done(function(data){
                resultDropdown.html(data);
            });
        } else{
            resultDropdown.empty();
        }
    });

    $(document).on("click", ".result p", function(){
        $(this).parents(".search-box").find('input[type="text"]').val($(this).text());
        $(this).parent(".result").empty();
    });
});
</script>
</head>
<body>
        <!-- <input type="button" onclick="add_fields();" value="Hozzáad"> -->
        <div class="search-box">
            <input id="food_name" type="text" autocomplete="off" placeholder="Étel keresése" />
            <div class="result"></div>
            <input style="width: 130px;" type="button" onclick="add_food();" value="Hozzáad">
            <input style="width: 130px;" type="button" onclick="submit_list();" value="Rendelés felvétele">
        </div>
        <div class="list">
            <ol id="list" name="food"></ol>
        </div>
</body>
</html>

<?php
   $added_foods = json_decode($_POST['foods_added']);
?>

The second code is order-food.php, which I would use to work with the array (in the end it would submit the items of the array into a database)

O. Collins
  • 38
  • 3
  • Make sure $_POST isn't empty before you try to decode it. If this is all in the same file, then it won't be populated when you first load it – aynber May 20 '19 at 17:56
  • `window.location.href = "order-food.php";` could be your problem. What happens when you disable that? – imvain2 May 20 '19 at 17:59
  • `data: JSON.stringify({ foods_added : foods_added })` – Alex Kudryashev May 20 '19 at 17:59
  • @imvain2 it still gives me Notice: Undefined index: foods_added in C:\xampp\htdocs\etterem\order-food.php on line 2 – O. Collins May 20 '19 at 18:01
  • @AlexKudryashev with this it gives me the same notice in the console – O. Collins May 20 '19 at 18:03
  • Your data key is the same name as your var - maybe try adding quotes around the key name: `data: { "foods_added" : JSON.stringify(foods_added) },` – MER May 20 '19 at 18:17

1 Answers1

1

You start the ajax request but then you refresh the page by calling

window.location.href = "order-food.php";

so the ajax request is halted and the page reloads, with no post values. Just delete that line, to let the request finish.

Then the method is set with the "type" parameter, not "method". So change the line in the ajax request from

method:"POST"

to

type:"POST"
Cosmin Staicu
  • 1,809
  • 2
  • 20
  • 27