I am hitting roadblock after roadblock in my quest to get this JSON usable by PHP, so I\'m wondering if someone can help me out here.
I have JSON being stored in the v
First of all, when dealing with JSON the best approach is to leave it alone as much as possible. Think if it as fragile goods. Anything you do to it could break it.
With that in mind, don't use stringify() and in fact you don't need to as JQuery will detect it and handle it for you (because they know it's fragile).
Second, the option data: in the $ajax() method needs to be given an object. Generally you would do something like this,
data: {mydata:divisionsJSON}
That way you can access the JSON on the backend via
$json = json_decode($_POST['mydata']);
Or, depending on how you have your divisions array set up, you could post it as the object data: is looking for and access it in PHP via $_POST['divisions_key'] = divisions_value; but that makes for all kinds of issues later and hard links the front end to the back end which is very bad (most of the time, exception is below).
Also, if you are expecting a JSON response you'll need to specify that in the original call using the dataType: 'JSON' option so JQuery can handle it appropriately.
$.ajax({
url: "divisions.php",
type: "post",
data: {mydata:divisions},
success: function(response){
$("#result").html(response.message);
},
error:function(response){
$("#result").html(response.message);
}
});
But, before we get too far, that division variable in JS is troubling. Where is that sourced from? Is it a form by any chance? If so, you can use serialize() such that
var divisions = $('#myform').serialize();
This will create key=>value pairs where the key is the name of the form field and the value is (obviously) the value of the field. You can access the values in PHP just as you would normally.
When considering the earlier question about how your array is structured, this is an acceptable case of posting data as the object. If it's a form then the form structure is going to be linked to the backend out of necessity anyway and so the direct use of the object in the data: option is just fine. It's that whole first concept of "leave it alone". The last case here leaves that object alone completely; from the time it leaves the DOM to the time it's received by the handler it's an object 100% of the time.
As @slamborne mentioned in the comment, the correct call is json_decode(file_get_contents('php://input'))
.
What your call is doing is actually making another call to divisions.php, which is why you're getting NULL back (it doesn't have any data to return to you, as divisions.php doesn't output anything).