skip to Main Content

I am trying to pass data to my php page:

<?php
var_dump($_POST);
if (isset($_POST['goal']) && isset($_POST['amount'])){


    $goal = $_POST['goal'];
    $amount = $_POST['amount'];



    $array = array(
      "goal" => $goal,
      "amount" => $amount

    );
    echo json_encode($array);


}

However as a result of var_dump $_POST I keep getting an empty array, for some reason my ajax doesn’t pass the neccessary data. I tried console.logging the value of fields that I am using and their value is correct it’s just that data doesn’t pass on the php page.

ajax:

<script type="text/javascript">
            $(document).ready(function () {
                //use button click event
                $("#goalBTN").click(function (e){
                    e.preventDefault();
                    let amount = $("#amount").val();
                    let goal = $("#goal_name").val();

                    $.ajax({
                        method: "post",
                        url: "target-modal-code.php",
                        data:JSON.stringify( {
                                amount: amount,
                                goal: goal
                            }),
                        contentType:"application/json",
                        success: function (response){
                            $("#response").text(response);
                            console.log(amount);
                            console.log(goal);
                        },
                        error: function(response) {
                            alert(JSON.stringify(response));
                        }
                    })
                });
            });

        </script>

And my form is inside a modal :


 <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="enrollLabel">Change your goal</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form action="target-modal-code.php" name="target-form" id="target-form">
                    <div class="modal-body">
                        <form action="">
                            <div class="mb-3 input-control">
                                <label for="amount">Cost</label>
                                <input type="number" class="form-control" id="amount" name="amount"
                                       placeholder="Amount">
                                <small class="message" id="message-password"></small>
                                <br>
                            </div>
                            <div class="mb-3 input-control">
                                <label for="goal_name">Goal</label>
                                <input type="text" class="form-control" id="goal_name" name="goal_name"
                                       placeholder="Goal">
                                <small class="message" id="message-password"></small>
                                <br>
                            </div>
                        </form>
                    </div>
                    <p class="response" id="response"></p>
                    <div class="modal-footer">
                        <div class="response">
                        </div>
                        <button type="button" id="goalBTN" class="btn btn-warning">Save changes</button>
                    </div>
                </form>
            </div>
        </div>

2

Answers


  1. format send ajax:

    $.ajax({
        ...
        data : {
            foo : 'bar',
            bar : 'foo'
        },
        ...
    });
    

    in your case: change data send format like:

    data: {
       amount: amount,
       goal: goal
    }
    
    Login or Signup to reply.
  2. Updated answer after some live testing with Network tab in firefox web dev tools

    The problem is that the current ajax code is not sending any of the elements because of wrong content-type. Let it detect content-type automatically. For jq ajax, default seems to be contentType: application/x-www-form-urlencoded even if you don’t provide it specifically.

    So, this worked:

    <script type="text/javascript">
            $(document).ready(function () {
                //use button click event
                $("#goalBTN").click(function (e){
                    e.preventDefault();
                    // let amount = $("#amount").val();
                    // let goal = $("#goal_name").val();
    
                    var formData = {
                      amount: $("#amount").val(),
                      goal_name: $("#goal_name").val(),
                    };
    
                    $.ajax({
                        method: "post",
                        url: "target-modal-code.php",
                        // datatype:"json",
                        //data:JSON.stringify(formData),
                        data: formData,
                        //contentType:"application/json",
                        //encode: true,
                        success: function (response){
                            $("#response").text(response);
                            // console.log(amount);
                            // console.log(goal);
                            console.log(formData);
                        },
                        error: function(response) {
                            alert(JSON.stringify(response));
                        }
                    })
                });
            });
    
        </script>
    

    After little bit of fiddling, I noticed that it works if you DON’T provide it contentType at all. Otherwise, AJAX won’t send GET or POST params to the server…. dont know why. I know it’s weird but that’s how it is in jquery ajax.

    I have intentionally kept the comments for you to see what all I have tried.

    So to summarize,

    • Don’t stringify the form data,
    • Don’t provide contentType to ajax
      request.

    Cheers.!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search