Reputation: 201
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 variable divisionsJSON:
var divisionsJSON = JSON.stringify(divisions);
Then I try to use .ajax to post with the following:
$.ajax({
url: "divisions.php",
type: "post",
data: divisionsJSON,
success: function(){
alert("success");
$("#result").html('submitted successfully');
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});
(I copied this from another question on SO, but have nothing in my html with the id="result" - I think I can delete that part [deletion confirmed])
Then, my divisions.php page contains the following:
<?php
$url = "divisions.php";
$json = file_get_contents($url);
$json = utf8_encode($json);
$elements = json_decode($json);
var_dump($elements);
?>
My inexperience with PHP/ajax combined with my frustration with getting this to work has made me try a bunch of different things. So far I've either gotten NULL or nothing when I load divisions.php. My gut tells me that it's a problem with the ajax, but I'm so inexperienced with PHP that I can't say with confidence that my PHP is correct enough to where I should be getting something back. I've tried var_dump, print_r, echo, absolutely nothing is showing up on divisions.php related to the actual PHP/JSON. Any and all help would be greatly appreciated!
Response with updated code:
I am getting NULL with the following php without the utf8 line, and string(0) "" when I added in the utf8 line:
<?php
$json = json_decode(file_get_contents('php://input'));
$elements = utf8_encode($json);
var_dump($elements);
?>
Any ideas?
Edited for full php page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>untitled</title>
<link rel="stylesheet" href="styles/reset.css" />
</head>
<body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="underscore.js"></script>
<script type="text/javascript" src="application.js"></script>
<script type="text/javascript" src="divisions.js"></script>
<?php
print_r($_POST);
?>
</body>
</html>
I've tried multiple lines for the php, print_r($_POST);, json_decode($_POST);, etc. but I'm changing so many things based on what I'm seeing on other SO's and this page that I'm really in a daze.
EDIT: Would this code, which I intended to make an array, not produce JSON? Because it doesn't seem like I'm working with JSON atm.
var divisions = [];
for (var i = 0; i < arr.length; i++) {
if(arr[i].value != "N/A"){
var obj = { "login": arr[i].login,
"value": "http://www.value.net/index/" + arr[i].value};
divisions.push(obj);}
Upvotes: 0
Views: 2537
Reputation: 9596
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).
Upvotes: 1
Reputation: 578
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.
Upvotes: 2