jquery – Can't post to PHP with AJAX-ThrowExceptions

Exception or error:

This question might have been asked a few times, but I couldn’t find any solutions to my problem.
So I created a list consisting of names of sweets (here Marshmallow, Milk Chocolate), I want to pass this as a string to a php file using POST. Here is my current code:

<script>
  function passJSON(){

    var endValues = $("#sweets").val().toString();
  $.ajax({
    type: "POST",
    url: "temporaryEchos.php",
    data: { sweetsAJAX : endValues },
    success: function(){
      var endValues = $("#sweets").val().toString();
      alert(endValues);
    }
  });
}
</script>
<button onclick="passJSON()">Click me to get data!</button>

$(“#sweets”).val() returns Marshmallow, Milk Chocolate, but I found I had to convert it to string for it to properly work.

Here’s my temporaryEchos.php

<?php


    $sweets = $_POST["sweetsAJAX”];

echo $sweets;

foreach ($sweets as $value){
  echo "Value: $value <br>";
}
echo "sweets set successfully!";
?>

after clicking submit the $.ajax success function returns Marshmallow, Milk Chocolate, but the PHP only echos “sweets set successfully!”. How could I go around this?

How to solve:

Change sweetsArray to sweetsAJAX

<?php
$sweets = $_POST["sweetsAJAX"];

echo $sweets;
?>

Leave a Reply

Your email address will not be published. Required fields are marked *