Why isn't json_encode working? - php

I'm trying to encode some user input I'm fetching from a database and then insert it into a textarea on click. Here's my code for encoding the data, sending the user to the textarea anchor, and then triggering my function.
$quote = "[url]" . $quote . "[/url]";
$quote = htmlspecialchars($quote, ENT_QUOTES);
$quote = json_encode($quote, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
echo "
<a href='#quickpost' value='quote'
onClick=\"quote(" . $quote . ")\" name='quote'>Quote</a>
Here's the quote() function:
function quote(originalpost){
oFormObject = document.forms['id1'];
oFormObject.elements['post'].value = originalpost;
};
I'm getting this error in firebug when I click it: SyntaxError: syntax error
Line 1
I'm a complete novice when it comes to JavaScript, so I could be missing something totally obvious.
I've looked and tried a lot of different encoding options and things for this, but I'm not getting anywhere.

Since JSON is native Javascript, you shouldn't quote it when declaring it in JS code or passing it around.
Try:
echo "
<a href='#quickpost' value='quote'
onClick='quote($quote)' name='quote'>Quote</a>";
Then inside your function, you may need to stringify the JSON:
oFormObject.elements['post'].value = JSON.stringify(originalpost);
For sanity's sake, get a copy of the JSON produced by json_encode and run it through the JSON lint utility to make sure it is valid.
See if that works. For browsers that don't have native stringify support, you can get the code for the function here.

Maybe you need to make sure you are sending a string to the quote function. For what I see you might be sending quote([url]... while you should be sending quote("[url]..." (note the quotation chars)

Since the data is from database, just output it as an array before you json encode it.
//array from database
$array = array();
//set the header
header("content-type:json/application");
return json_encode($array);
Then retrieve the encoded json as responseText.
var data = $.ajax({
url:"",
type:"json",
cache:false,
async:false
}).responseText;
var encodedData = JSON.parse(data);
Now you have a valid json object which is encodedData

Related

Print json in pretty format using php code

I have array like below.
$resultArr = array();
$resultArr['status code'] = 200;
$resultArr['result'] = "Success";
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
return $json;
This is giving result like below
"{\n \"status code\": \"200\",\n \"result\": \"Success\",\n}"
without Pretty_print the result is like below
"{\"status code\":\"200\",\"result\":\"Success\"}"
I want response to be like this
{
"status code": 200,
"result": "Success"
}
Is something like this can be done pls, I am using PHP, Running the request in postman and the response are mentioned above
Note: I need to avoid using echo, because we are using code sniffers in project, so echo is not recommended.
You used JSON_PRETTY_PRINT for beautify output purpose,
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
If you want to use it as response remove that parameter,
$json = json_encode($resultArr);
Above line should work.
First of all, remove the JSON_PRETTY_PRINT flag.
Secondly, your problem is with the backslashes (\). These are escape characters. I don't know how you are printing your json or how you are viewing it.
If I do:
echo $json;
It outputs:
{"status code":200,"result":"Success"}
The backslashes are probably added because you're doing an AJAX request. In order to solve this, you could use jQueries .parseJSON() or add dataType: "json" to your ajax request.
And if you really don't want the backslashes to be added:
$json = json_encode($resultArr, JSON_UNESCAPED_SLASHES);
Update
It might help to output using the following header:
header('Content-Type: application/json');
1. for Output Of API You Can Use Api:
header('Content-Type: application/json');
2. Using JSON_PRETTY_PRINT
$json = json_encode($resultArr,JSON_PRETTY_PRINT);
3. You want To Display In Chrome
https://addons.mozilla.org/en-US/firefox/addon/json-handle/?src=recommended

Form post has "%10" written by user - json_decode() fails with urldecode()

Was so awesome of the customer to type "%10" instead of "10%"
0_o
$PACKAGE_json_decode = json_decode(urldecode(($_POST['textarea']), true);
print_r($PACKAGE_json_decode); // LENGTH 0
foreach($PACKAGE_json_decode as $row){
}
ERROR:
"Message: Invalid argument supplied for foreach()"
How do I urldecode without causing the %10 to take on a different meaning when sent back via AJAX?
And decode seems to produce that square character I cannot paste here... you know ... looks sorta like "[]"
*The string needs to be the same for the client when they get it back - they save it with a % they want it back with a %.
- Any suggestions about replacing it?
The % character is used in URL encoding. Either you remove % from the front end before passing to the server or you deal the same in the server side.
You could encode your request send by Ajax directly, such as below:
$.ajax({
type:'POST',
dataType: 'json',
...
Or like this:
JSON.stringify('%10');
Inside your PHP, just json_decode() now, as below.
$PACKAGE_json_decode = json_decode($_POST['textarea']);
Like this, your %10 will become "%10", et voila!!!
Please use the following code and let me know where is it breacking ?
<?php
$url_encode = urldecode("sampleTextWith%");
echo '<b>Ecoded URL </b>'. $url_encode."<br>";
$obj = new StdClass();
$obj->text = $url_encode;
$encoded_json = json_encode($obj);
echo '<b>Encoded JSON </b>'. $encoded_json."<br>";
$decoded_json = json_decode($encoded_json);
echo "<b>Decoded JSON </b>";
print_r($decoded_json);
echo "<br>";
foreach($decoded_json as $row){
echo "<b>Row Value : </b>". $row."<br>";
}
?>

PHP: How to json encode of hindi language in response

I am working with a translation API but here is an issue. I am using JSON in response and when I do json_encode of Hindi then the out is like "\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948"
My code is given below
$data = array();
$data['hindi'] = 'यह कार है';
$data['english'] = 'This is car';
echo json_encode($data); die;
and the response is
{"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"}
If you are running PHP 5.4 or greater, pass the JSON_UNESCAPED_UNICODEparameter when calling json_encode
Example:
$data = array();
$data['hindi'] = 'यह कार है';
$data['english'] = 'This is car';
echo json_encode($data, JSON_UNESCAPED_UNICODE);
die;
This is correct json and when you display it in the browser and / or parse it, it will result in an object with the correct keys and values:
var json_string = '{"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"}',
json = JSON.parse(json_string);
// or directly:
var json2 = {"hindi":"\u092f\u0939 \u0915\u093e\u0930 \u0939\u0948","english":"This is car"};
console.log(json_string);
console.log(json);
console.log(json2);
document.write(json_string);
document.write('<br>');
document.write(json.hindi);
document.write('<br>');
document.write(json2.hindi);
The reason for this is likely that these characters are not in UTF-8 (I could not find them, at least). From the PHP documentation on json_encode:
All string data must be UTF-8 encoded.
This means that it will have to convert it to a 'description' of the characters. Do not worry, if you decode it again it will very likely be correct.
I have a solution to this problem. It works fine for me.
$data = array();
$data['hindi'] = base64_encode('यह कार है');
$data['english'] = 'This is car';
$encoded_text=json_encode($data);
To retrieve the hindi part of data:
$hindi=base64_decode(json_decode($encoded_text)->hindi);

Get Json From php file

I am new to jQuery. I have got an error when I try to get data from fileresult.php.
fileresult.php
$return_arr = array();
$row_array['status'] = 'Ok';
$row_array['message'] = 'good'
array_push($return_arr, $row_array);
echo json_encode($return_arr);
JSON output
[{"date":"2014-03-15","status":"ok","message":"good"}]
get_result.js
$.post('file.php', $("form").serialize(), function(data) {
var status = data['status'];
alert(status);
});
When I alert data, it shows undefined. Somebody please help me. How can I show the correct data.
You have two problems.
You are outputting "HTML"
PHP defaults to claiming that its output is HTML. jQuery will see this claim and treat it as such instead of parsing it as JSON.
Override PHP's default with:
header("Content-Type: application/json");
You have an array
You are accessing data.status but the top level data structure you are outputting is an array so you need data[0].status with that data.
You don't have multiple objects though, so (unless you plan to add more in the future) it would make more sense to return
{"date":"2014-03-15","status":"ok","message":"good"}
instead of
[{"date":"2014-03-15","status":"ok","message":"good"}]
So remove everything to do with $return_arr and:
echo json_encode($row_array);

JSON object "undefined" error in Javascript

I am uploading a file using PHP and want to return the file name and the file status to javascript. In PHP I create the json object by:
$value = array('result' => $result, 'fileName' => $_FILES['myfile']['name']);
print_r ($value);
$uploadData = json_encode($value);
This creates the json object. I then send it to a function in javascript and recieve it as a variable called fileStatus.
alert (fileStatus);
It displays
{"result":"success","fileName":"cake"}
which should be good. But when I try and do
fileStatus.result or fileStatus.fileName
I get an error saying that they are undefined. Please help I'm really stuck on this. Thanks.
The fileStatus is just a string at this point, so it does not have properties such as result and fileName. You need to parse the string into a JSON object, using a method such as Firefox's native JSON.parse or jQuery's jQuery.parseJSON.
Example:
var fileStatusObj = jQuery.parseJSON(fileStatus);
If the alert displays {"result":"success","fileName":"cake"} then you probably still have to turn the string into a JSON object. Depending on the browsers you are developing for you can use the native JSON support or the JSON.org implementation to turn your string into an object. From there on it should work as expected.
When you are setting the variable, do not put quotes around it. Just set the variable like this:
var fileStatus = <?php echo $uploadData; ?>;
or:
var fileStatus = <?=$uploadData?>;
Do not do this:
var fileStatus = '<?php echo $uploadData; ?>';

Categories