So I'm posting an array of objects in a JSON string using javascript to a PHP script and I'm having real problems decoding it in the php.
My javascript is as follows:
$.ajax({
type: 'POST',
url: "question_save.php",
data: {myJson: JSON.stringify(jsonArray)},
success: function(data){
alert(data);
}
});
The string sent to the PHP looks like this:
[{"content":"Question text"},{"answerContent":"Some answer text","score":"234","responseChecked":0,"responseContent":""},{"answerContent":"","score":"0","responseChecked":0,"responseContent":""}]
If I echo $_POST['myJson'] I get this:
[{\"content\":\"Question text\"},{\"answerContent\":\"Some answer text\",\"score\":\"234\",\"responseChecked\":0,\"responseContent\":\"\"},{\"answerContent\":\"\",\"score\":\"0\",\"responseChecked\":0,\"responseContent\":\"\"}]
Yet when I want to decode the JSON and loop through it like this...
$json = $_POST['myJson'];
$data = json_decode($json, true);
foreach ($data as &$value) {
echo("Hi there");
}
...I get this error:
Warning: Invalid argument supplied for foreach() in /home/thecrime/public_html/test1/question_save.php on line 15
I really don't understand what silly mistake I'm making, is it something to do with the back slashes?
Any help much appreciated!
Thanks,
-Ben
Use stripslashes ( $string ) - http://php.net/manual/en/function.stripslashes.php
This should work
$json = $_POST['myJson'];
$json_string = stripslashes($json)
$data = json_decode($json_string, true);
// simple debug
echo "<pre>";
print_r($data);
However, as already pointed by the others, it's better to disable magic_quotes_gpc.
Open your php.ini file and search for this row:
magic_quotes_gpc = On
Set it to Off and restart the server.
This has to do with Magic Quotes
Is better to disable this annoying old feature and forget those problems.
You can disabled following these instructions.
Related
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
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>";
}
?>
Pardon me if I am making a silly mistake here... But I am little new to PHP...
I have been stuck at this for long time.
I have tried several methods but I am only able to pass ONe table row , not multiple rows
I've even tried with the following approach, but I landed with the same error.
http://www.electrictoolbox.com/json-data-jquery-php-mysql/
Here's what I am trying to do :
1) Make Ajax call using JQuery, to fetch data from server.
$.ajax({
url: 'test.php', //the script to call to get data
data: "",
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
//use "data"
}
2) fetch table data from MySql database, using PHP.
$result = mysql_query("SELECT username,characterType FROM usertable");
3) pass ALL of the rows as JSON data, back to the calling function.
//This works , Returns one row and I am able to get the result back at AJAX end
$array = mysql_fetch_row($result);
echo json_encode($array);
mysql_fetch_assoc($result) FAILS with the following error :
XML Parsing Error: no element found Location: moz-nullprincipal:{6b1***-****somecrap numbers****-***86} Line Number 17, Column 3:
$array = mysql_fetch_assoc($result);
echo json_encode($array);
I have even tried using mysql_fetch_array($result, MYSQL_NUM) as suggested in the other relevant questions, but I am not able to workaround the problem.
Any Help is greatly appreciated.
============
UPDATE:
I may be wrong but just wanted to know, if this could be the possibility or not... Can this be a local setup related issue ? A Configuration mistake .. ?
I have done my localhost setup using "XAMPP installation" [ Apache / MySQL / Tomcat ... bundled in one package ] ...
When I run the file as "PHP application" it runs just fine ... I am able get "all rows" But when I deploy the code on my apache servers it doesn't run ... The whole php file comes as a response , with "XML parsing Error" [ I am using firebug to track the response ]
Thanks
Pranav
A few things to note here:
As Rup mentioned, $array = mysql_fetch_row($result); only returns a single row.
The other thing is that test.php does not currently return a JSON object; to see whats going on, it helps to comment out dataType: 'json', and use console.log(data); to see what is being returned. Your response probably looks something like this:
["someUsername","someChartype"]
The format of the object you are expecting is probably something more like:
[{"username":"foo","chartype":"admin"},
{"username":"bar","chartype":"user"},
{"username":"fum","chartype":"guest"}]
To get the format of the associative array, use mysql_fetch_assoc($result) instead; that will give
{"username":"someUsername","chracterType":"someChartype"}
To summarize, update your php code to:
Loop through your results, pushing them onto an array.
Encode the entire array at the end
$outputArray = array();
while( $row = mysql_fetch_assoc( $result ) ){
array_push($outputArray, $row);
}
echo json_encode($outputArray);
Take a look at How to build a JSON array from mysql database for more info. Also, as one of the answers mention, its worth using PDO rather than mysql_*
Don't start manually composing a JSON string as #Tuanderful indicated. Let json_encode() handle that -- just give it the right data. Try something like this:
$records = array();
while ( $record = mysql_fetch_assoc( $result ) ) {
$records[] = $record;
}
echo json_encode( $records );
Well I would to like this:
$.ajax({
url: 'test.php', //the script to call to get data
//data: "",
dataType: 'json', //data format
success: somevar
})
var somevar = function(data) //on recieve of reply
{
//use "data"
somevar2 = jQuery.parseJSON(data)
//now You can enter each row/cell from db(/php) like this
// somevar2[0] would be the first row from php
//if You want to do something with every line You can use:
//$.each(somevar2, function(key,value){
//$('#divname').html(value.cellnameoftable)
}
I hope it will help ;)
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
i have this public JSON https://raw.github.com/currencybot/open-exchange-rates/master/latest.json and i need to extract data from it, right now i tried something like this:
$input = file_get_contents("https://raw.github.com/currencybot/open-exchange-rates/master/latest.json");
$json = json_decode($input);
echo $json[rates]->EUR;
but i obtain a blank page, any suggestion? Thanks !! Ste
json_decode either returns an object, or an array (when you use the second param). You are trying to use both.
Try:
$json = json_decode($input);
echo $json->rates->EUR;
OR
$json = json_decode($input, true);
echo $json['rates']['EUR'];
As to the blank page, please add the following to the top of your script:
error_reporting(E_ALL);
init_set('display_errors', true);
A 500 Error indicates you are unable to resolve that url using file_get_contents.
Check here for more information.
Read the help for json_decode ... without the second parameter it returns and object not an array ...
Either :
$json = json_decode($input);
echo $json->rates->EUR;
or
$json = json_decode($input,true);
echo $json['rates']['EUR'];
Try:
$arr = json_decode($input, true);
var_dump($arr);
echo $arr['rates']['EUR'];
Further Reading:
http://de.php.net/manual/de/function.json-encode.php
For anexample with cURL and SSL read this:
http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/
The link looks like starting with https, while file_get_contents can't deal with SSL. My suggestion is using curl.