Jquery json echo - php

EDIT
Solved it. It was before the ajax call and, hence, this code. Thank you all for the answers.
I can't find anybody with this problem. I have a AJAX call to a PHP script that returns a JSON response.
I fetch the values from a database into an array:
while($row = mysql_fetch_array($ret)){
$temp = array(
'id' => $row['id_reserva'],
'start' => $row['data_inicio'],
'end' => $row['data_fim'],
'title' => $row['descricao']
);
$js[] = $temp;
}
Headers:
header('Content-type: application/json');
And echo:
echo json_encode($js);
There is no return whatsoever, just a null string.
What is really bugging me is that if instead of this I create a json string with the previous result directly in the code:
$temp = '[{"id":"3914", "start": "2011-08-25 09:00:00",
"end":"2011-08-25 18:00:00", "title":"asdasdasd"},
{"id":"3915", "start": "2011-08-25 09:00:00",
"end":"2011-08-25 18:00:00", "title":"asdasdasd"}]';
echo $temp;
It works.
Tried changing the file codification, comparing the strings, checking for some problem with chars, and nothing.
Anybody?
Cheers

you have to encode it. try
echo json_encode($js);

You need to json encode array:
echo json_encode($js);

You're not outputting as JSON?
echo json_encode($js);
With your method, when jQuery gets the response and cannot parse the JSON it will return the empty string as you have experienced.

Process of elimination..
can you print_r ($js) and get output?
Take out the header(); statement, does anything appear?
Do you have error_reporting and display_errors turned on?
You don't seem to initializing 'js' ($js = array()). If you get the literal string 'null' back, this could simply imply that your query is not returning any results.
I could add this statement to almost every long-winded PHP requestion on stack overflow:
Go through your code step by step and echo what you expect the contents of variables to be at that point. Then you'll slowly isolate exactly where your issue is; there's nothing wrong with your code as-is.

Are you not making a multi-dimentional array with $js[] = $temp; and then encoding that? Try just doing json_encode($temp);

Related

At a loss with JSON, PHP, AS3: Cannot trace correct value

I have used JSON objects before and they work perfectly but the JSON objects that I made before have been from a result of fetched MySQL entries. Now, I am trying to make my own JSON object through an array in PHP and it shows correctly in the database but I cannot access any of the values like before.
$chatArray = array(
array(
'chatusername' => 'Troy',
'chatuserid' => '123',
'chatmessage' => 'Hello World'
),
array(
'chatusername' => 'Nick',
'chatuserid' => '124',
'chatmessage' => 'Testing'
));
$inputArray = json_encode($chatArray);
That is what I input into my database and like I said it works good. Then I call for it in a separate .php and get this
{"chat":"[{\"chatuserid\": \"123\", \"chatmessage\": \"Hello World\", \"chatusername\": \"Troy\"}, {\"chatuserid\": \"124\", \"chatmessage\": \"Testing\", \"chatusername\": \"Nick\"}]"}
It throws the "chat" out front which is the column name in my database which I am not sure why.
When I trace it I can only seem to trace it by
var messageArray:Object = JSON.parse(event.target.data);
trace(messageArray.chat);
Any time I try to reference say messageArray.chat.chatusername it returns an error.
I'm sorry I know it is probably a simple solution but I have been searching and working at it for a few hours now.
Any help is much appreciated! Thank you!
From the PHP code that generates your JSON output:
$stmt = $conn->prepare("SELECT chat FROM markerinfo WHERE markerid='$chatid'");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
Keep in mind that the chat column in your database contains a JSON-string.
This code is not decoding the JSON-string in your database, so $result will be an array containing a JSON-string as well:
$result = [
'chat' => '[{"chatusername":"Troy","chatuserid":"123","chatmessage":"Hello World"},{"chatusername":"Nick","chatuserid":"124","chatmessage":"Testing"}]'
];
By passing that array through json_encode(), you're double-encoding your JSON-string.
For your purposes, you can probably get away with:
echo $result['chat'];
But, if you want the chat column name to be included in your output, you will have to decode the stored JSON first:
$result['chat'] = json_decode($result['chat']);
echo json_encode($result);
Probably this is related to the php side when it encodes your array, it will escape it with slashes, and this confuses the JSON parsing in your JS side. Try to add the JSON_UNESCAPED_SLASHES option to your json_encode function like this:
$inputArray = json_encode($chatArray, JSON_UNESCAPED_SLASHES);
Check the json_encode function documentation for more details:
http://php.net/manual/en/function.json-encode.php

PHP Using ($_GET['url']) and then displaying that json data?

<?php
function get_stuff()
{
($_GET['http://****RemovedForSecurityPurposes****.repairshopr.com/api/v1/tickets?api_key=****RemovedForSecurityPurposes****']);
echo $_GET;
}
get_stuff();
?> /* Yes, Pointless closing tag, I'm cool like that. */
For some reason when I run this code the output I'm getting is "Array" and I can't figure out why? I know it is an array that I'm getting from the URL but I thought it would just print in whatever format its in? Am I missing something?
Thanks In advance!
You cannot pass website URL to $_GET.
You should use file_get_contents()
$content = file_get_contents('http://YOUR_URL');
If you have valid json then you can convert it to an array.
$data = json_decode($content, true);
then print it,
echo '<pre>'; print_r($data);
The Message of OP when I run this code the output I'm getting is
"Array".
You need to use file_get_contents to read a file from a remote server. If your file response an array then you have to use print_r or var_export or var_dump. Or if your file response is a string(json) then you need to store it in a variable and apply a decode method.
function get_stuff(){
$response = file_get_contents('http://****RemovedForSecurityPurposes****.repairshopr.com/api/v1/tickets?api_key=****RemovedForSecurityPurposes****');
print_r($response); // if array
$arr = json_decode($response); // decode of json
print_r($arr);
}
get_stuff();
I think you will understand what i mean. Let me know if you are useful or need some help.

Why is JSON return showing open curly bracket instead of data?

So I'm returning the data from twitter, and for some reason I cannot return the count data, all it returns when I echo it is the open curly bracket.. here is how I am trying to echo it.
"statuses": [],
"search_metadata": {
"completed_in": 0.008,
"max_id": 668543797022826500,
"max_id_str": "668543797022826503",
"query": "URL",
"refresh_url": "URL",
"count": 15,
"since_id": 0,
"since_id_str": "0"
}
That is what the code below returns.. all I am trying to do is echo the count data but it doesn't.. all it prints instead of the 15 is {
$counter = $connection->get("https://api.twitter.com/1.1/search/tweets.json?q=".$this->url );
$ajsn = json_encode($counter);
echo $ajsn['search_metadata']['count'];
Could anyone explain to me why this isn't printing?
try this:
$ajsn = json_decode($counter, true);
echo $ajsn['search_metadata']['count'];
When you run this:
$counter = $connection->get("https://api.twitter.com/1.1/search/tweets.json?q=".$this->url );
$ajsn = json_encode($counter);
echo $ajsn['search_metadata']['count'];
you get "{", you say.
That you get a single character should probably be expected because json_encode returns a string, not an array. And a key index into a string should get you an error, or at least a warning; if it doesn't, it probably returns the integer equivalent of the string, which is zero. So you're getting the zeroth (the first) character of a JSON encoding.
That it is a "{" is actually good news. It means that json_encode did return something: the curly brace is the opening of a JSON object.
What you should do is verify what {$counter} is. Is it an object? An array? Then you can echo it appropriately. For example $counter->search_metadata->count.
Otherwise, since $ajsn is a valid string, a quick and dirty ugly fix is to convert it to an array again:
$counter = $connection->get("https://api.twitter.com/1.1/search/tweets.json?q=".$this->url );
$ajsn = json_encode($counter); // Convert whatever to string
$ajsn = json_decode($ajsn, true); // Convert ajsn to associative array
echo $ajsn['search_metadata']['count'];
Also, activate all error and warning output. You should have gotten something to tell you where you stood, and you got nothing - that can make debugging needlessly complicated. Activate screen display or at the very least file logging using error_reporting and the appropriate php.ini settings.

json_encode - formatting issue?

I am requesting my output look like this:
Response
{
error_num: 0
error_details:
[
{
"zipcode": 98119
},
{
"zipcode": 98101
}
]
}
The values are irrelevant for this example.
My code looks like this:
$returndata = array('error_num' => $error_code);
$returndata['error_details'] = $error_msg;
$temp_data = array();
$temp_value = '';
foreach ($zipcodes_array as $value) {
//$temp_data['zipcode'] = $value;
//$temp_value .= json_encode($temp_data);
$temp_value .= '{"zipcode":$value},';
}
//$returndata['test'] = $temp_value;
$returndata['zipcodes'] = $temp_value;
echo json_encode($returndata);
My output varies depending on my different attempts (which you can see with the commented out things) but basically, I don't understand how the 3rd part (the part with the zipcodes) doesn't have a key or a definition before the first open bracket "["
Here is the output for the code above:
{"error_num":0,"error_details":"","zipcodes":"{\"zipcode\":11111},{\"zipcode\":11112},{\"zipcode\":11113},{\"zipcode\":22222},{\"zipcode\":33333},{\"zipcode\":77325},{\"zipcode\":77338},{\"zipcode\":77339},{\"zipcode\":77345},{\"zipcode\":77346},{\"zipcode\":77347},{\"zipcode\":77396},{\"zipcode\":81501},{\"zipcode\":81502},{\"zipcode\":81503},{\"zipcode\":81504},{\"zipcode\":81505},{\"zipcode\":81506},{\"zipcode\":81507},{\"zipcode\":81508},{\"zipcode\":81509},"}
Obviously i did not show the variables being filled/created because its through MySQL. The values are irrelevant. Its the format of the output i'm trying to get down. I don't understand how they have the "zipcode": part in between {} brackets inside another section which appears to be using JSON_ENCODE
It is close but see how it still has the "zipcodes": part in there defining what key those values are on? My question is, is the "response" above being requested by a partner actually in JSON_ENCODE format?? or is it in some custom format which I'll just have to make w/out using any json features of PHP? I can easily write that but based on the way it looks in the example above (the response) I was thinking it was JSON_ENCODE being used.
Also, it keeps putting the \'s in front of the " which isn't right either. I know it's probably doing that because i'm json_encode'ing a string. Hopefully you see what i'm trying to do.
If this is just custom stuff made to resemble JSON, I apologize. I've tried to ask the partner but I guess i'm not asking the right questions (or the right person). They can never seem to give me answers.
EDIT: notice my output also doesn't have any [ or ] in it. but some of my test JSON_ENCODE stuff has had those in it. I'm sure its just me failing here i just cant figure it out.
If you want your output to look like the JSON output at the very top of your question, write the code like this:
$returndata = array('error_num' => $error_code);
$returndata['error_details'] = array();
foreach ($zipcodes_array as $value) {
$returndata['error_details'][] = array('zipcode' => (int)$value);
}
echo 'Response ' . json_encode($returndata);
This will return JSON formatted like you requested above.
Response
{
error_num: 0
error_details:
[
{
"zipcode": 98119
},
{
"zipcode": 98101
}
]
}
Can you just use single ZipCode object as associative array, push all your small ZipCode objects to the ZipCodes array and encode whole data structure. Here is the code example:
$returndata = array(
'error_num' => $error_code,
'error_details' => array()
);
foreach ($zipcodes_array as $value) {
$returndata['error_details'][] = array('zipcode' => $value);
}
echo json_encode($returndata);

how to use JSON.stringify and json_decode() properly

Im trying to pass a mulitidimensional Javascript array to another page on my site by:
using JSON.stringify on the array
assigning the resultant value to an input field
posting that field to the second page
using json_decode on the posted value
then var_dump to test
(echo'ing the posted variable directly just to see if it came through
at all)
Javascript on page one:
var JSONstr = JSON.stringify(fullInfoArray);
document.getElementById('JSONfullInfoArray').value= JSONstr;
php on page two:
$data = json_decode($_POST["JSONfullInfoArray"]);
var_dump($data);
echo($_POST["JSONfullInfoArray"]);
The echo works fine but the var_dump returns NULL
What have I done wrong?
This got me fixed up:
$postedData = $_POST["JSONfullInfoArray"];
$tempData = str_replace("\\", "",$postedData);
$cleanData = json_decode($tempData);
var_dump($cleanData);
Im not sure why but the post was coming through with a bunch of "\" characters separating each variable in the string
Figured it out using json_last_error() as sugested by Bart which returned JSON_ERROR_SYNTAX
When you save some data using JSON.stringify() and then need to read that in php. The following code worked for me.
json_decode( html_entity_decode( stripslashes ($jsonString ) ) );
Thanks to #Thisguyhastwothumbs
When you use JSON stringify then use html_entity_decode first before json_decode.
$tempData = html_entity_decode($tempData);
$cleanData = json_decode($tempData);
You'll need to check the contents of $_POST["JSONfullInfoArray"]. If something doesn't parse json_decode will just return null. This isn't very helpful so when null is returned you should check json_last_error() to get more info on what went wrong.
None of the other answers worked in my case, most likely because the JSON array contained special characters. What fixed it for me:
Javascript (added encodeURIComponent)
var JSONstr = encodeURIComponent(JSON.stringify(fullInfoArray));
document.getElementById('JSONfullInfoArray').value = JSONstr;
PHP (unchanged from the question)
$data = json_decode($_POST["JSONfullInfoArray"]);
var_dump($data);
echo($_POST["JSONfullInfoArray"]);
Both echo and var_dump have been verified to work fine on a sample of more than 2000 user-entered datasets that included a URL field and a long text field, and that were returning NULL on var_dump for a subset that included URLs with the characters ?&#.
stripslashes(htmlspecialchars(JSON_DATA))
jsonText = $_REQUEST['myJSON'];
$decodedText = html_entity_decode($jsonText);
$myArray = json_decode($decodedText, true);`
I don't how this works, but it worked.
$post_data = json_decode(json_encode($_POST['request_key']));

Categories