I have a ajax call calling a php file who runs a long php function which returns a JSON encoded array/object. Now I need to send HTML also into the ajax response. I thought about sending the HTML inside the array.
Is that a good practise?
Right now I cannot get it working, I get a NULL as value for that property. Don't know why.
$statHTML = '<table>';
foreach ($toHTML as $key=>$value) {
$statHTML.= '
<tr class="'.$key.'">
<td class="side">'.$value[0].'</td>
<td>'.$value[2].' '.$value[1].'</td>
</tr>';
}
$statHTML.= '</table>';
// echo $statHTML; // - this works
//function return
$answer = array('mostSearched'=>$mostSearched,
'timeOfDay' => $timeOfDay,
'mostSearchedDays'=>$mostSearchedDays,
'statHTML' => $statHTML
);
return json_encode($answer);
The ajax response from the console before the JSON.parse():
{
"mostSearched": {
"title": "Most serached houses",
"colNames": [21],
"rowNames": [2013],
"rows": [1]
},
"timeOfDay": {
"title": "Time of search",
"colNames": ["07:30"],
"rowNames": ["07:30"],
"rows": [
[1]
]
},
"mostSearchedDays": {
"title": "Most searched days",
"colNames": ["2013-12-21", "2013-12-22", "2013-12-23", "2013-12-24", "2013-12-25", "2013-12-26", "2013-12-27"],
"rowNames": ["2013-12-21", "2013-12-22", "2013-12-23", "2013-12-24", "2013-12-25", "2013-12-26", "2013-12-27"],
"rows": [
[1, 1, 1, 1, 1, 1, 1]
]
},
"statHTML": null
}
From php.net:
Parameters
value
The value being encoded. Can be any type except a resource.
All string data must be UTF-8 encoded.
So use:
$answer = array('mostSearched'=>$mostSearched,
'timeOfDay' => $timeOfDay,
'mostSearchedDays'=>$mostSearchedDays,
'statHTML' => utf8_encode($statHTML)
);
return json_encode($answer);
Most likely the build-in JSON parser used by PHP cannot properly parse the HTML, the easiest way to solve the issue is to base64 encode the html on the server, and then decode it on the client, using either the newer atob and btoa base64 methods, or one of the many polyfills out there.
use base64_enccode in this at the time of conversion
$answer = array('statHTML'=>base64_encode('<h1>html in here</h1>'));
echo json_encode($answer);exit;
And at the time of getting response from ajax
atob(response.statHTML);
Hope you understand how it works
Related
I want to read the json data on the page http://mattrb.com/txt.txt
For example, let's say I want to get the name "Bulbasaur." I have this code:
<?php
$file = file_get_contents("http://mattrb.com/txt.txt");
$json = json_decode($file);
echo $json->1->name;
?>
This code causes the php to simply not load. Is this because you can't use a number? Next I tried this:
<?php
$file = file_get_contents("http://mattrb.com/txt.txt");
$json = json_decode($file);
$num = 1;
echo $json->$num->name;
?>
This allows the php to load, but still returns nothing. What am I doing wrong?
Your json is invalid. Please check at http://jsonlint.com/.
Also you can access "1" in php like this: echo $json->{1}->name;
Your json file isn't valide You have a comma problem item number 135 try to delete it so you can parse the file .
"135": {, //the problem of your json data is here
"levels": [5, 15],
"probability": 4 "name": "Jolteon",
"attack": 65,
"defense": 60,
"type": "electric",
"moves": [
"tackle",
"thundershock",
"thunder"
],
"curve": 1.6
},
Your json should not contain newline and other invalid characters.
In other words - your json is invalid. json_decode does not work on the file.
$file = file_get_contents("http://mattrb.com/txt.txt");
var_dump(json_decode($file));
// NULL
I assume some of you might be already rolling their eyes since my topic has been dealt with so often in this forum. However, I haven't found any solution yet in this forum.
I want to parse a JS Object to a receiving PHP Site via JSON. I already read numerous times about the right parameters for the XMLHttpRequest-Header and its impact on the PHP part. I tried the very same solutions given in several other forums, but IT SIMPLY DOESN'T WORK for me. I've been working on this whole issue for four month now. I really need some advice.
Here is my JSON encoding JS Script:
function saveToDB(knotItems) {
var txtobj = knotItems;
var json = JSON.stringify(txtobj);
var url = "http://localhost/projektplaner/tools/DBConnection/writeFileToDB.php";
rq = new XMLHttpRequest();
rq.open("post", url, true);
rq.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
rq.send("project=" + json);
rq.onreadystatechange = window.open(url);
}
This is the JS-generated object array knotItems after being stringified by JSON:
[{
"rank": 1,
"name": "Baugrube",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "19.5.2016",
"faz_timestamp": 1463680336402,
"d": "2",
"parallelTask": "seriell",
"fez": ["2016-05-21T17:52:16.402Z", "21.5.2016", "NaN2"],
"fez_dateObj": "2016-05-21T17:52:16.402Z",
"fez_string": "21.5.2016"
}, {
"rank": 2,
"name": "Kellerwände",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "21.5.2016",
"faz_timestamp": 1463853136402,
"d": "4",
"parallelTask": "seriell",
"fez": ["2016-05-25T17:52:16.402Z", "25.5.2016", "NaN4"],
"fez_dateObj": "2016-05-25T17:52:16.402Z",
"fez_string": "25.5.2016"
}, {
"rank": 3,
"name": "Kellerdecke",
"faz_obj": "2016-05-30T17:52:16.402Z",
"fazInDays": null,
"faz_string": "25.5.2016",
"faz_timestamp": 1464198736402,
"d": "5",
"parallelTask": "seriell",
"fez": ["2016-05-30T17:52:16.402Z", "30.5.2016", "NaN5"],
"fez_dateObj": "2016-05-30T17:52:16.402Z",
"fez_string": "30.5.2016"
}]
The reason I post the variable content is to show that all object keys are in double quotes, as required by PHP's json_decode.
This is my PHP receiving script:
if(isset($_POST['project']))
{
echo json_decode($_POST['project'],true);
}
else
{
echo "Keine Daten"; // No Data
}
This is the parameter payload that can be seen via Firebug analysis:
project:"[{"rank":1,"name":"Baugrube","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"19.5.2016","faz_timestamp":1463680336402,"d":"2","parallelTask":"seriell","fez":["2016-05-21T17:52:16.402Z","21.5.2016","NaN2"],"fez_dateObj":"2016-05-21T17:52:16.402Z","fez_string":"21.5.2016"},{"rank":2,"name":"Kellerwände","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"21.5.2016","faz_timestamp":1463853136402,"d":"4","parallelTask":"seriell","fez":["2016-05-25T17:52:16.402Z","25.5.2016","NaN4"],"fez_dateObj":"2016-05-25T17:52:16.402Z","fez_string":"25.5.2016"},{"rank":3,"name":"Kellerdecke","faz_obj":"2016-05-30T17:52:16.402Z","fazInDays":null,"faz_string":"25.5.2016","faz_timestamp":1464198736402,"d":"5","parallelTask":"seriell","fez":["2016-05-30T17:52:16.402Z","30.5.2016","NaN5"],"fez_dateObj":"2016-05-30T17:52:16.402Z","fez_string":"30.5.2016"}]"
HTTP Status Code is always 200 (OK).
And this is what I get from the PHP File.
Notice: Undefined index: project in C:\xampp\htdocs\projektplaner\tools\DBConnection\writeFileToDB.php on line 7
Keine Daten
I don't want to sound melodramatic or anything, but I'm about to go ape. I just can't see what the hell is wrong. Could it be a Server configuration issue?
I really, really appreciate your help.
Thank you very much in advance.
I would like to get an array from my JSON in php.
This way I get the JSON string from URL in my android application:
JSONObject json = jParser.makeHttpRequest(url_all_user, "GET", paramstodb);
To receive [phone=123] in php I use this:
if (isset($_GET["phone"])) {
$phone = $_GET['phone'];
That is working for one phonenumber, but now I need more than one phonenumber.
The data in Logcat (reported with "Log.d("to php: ", paramstodb.toString())" ) is displayed as:
to php:﹕ [phone=[0127361744, 0132782422, 0137173813, 0142534646, 0123617637435, 013391339494, 01383375633, 013878942423, 013891748422, 01389487285, 014434354234, 01848481371, 018831789414, 021238133441231, 021371689411, 02183718454, 123, 456]]
How can I get all numbers in an array in php?
This is not working so far:
if (isset($_GET["phone"])) {
$phone = $_GET['phone'];
$phpArray = json_decode($phone, true);
I hope you can help me again ;-)
If the JSON input to the PHP script really is this JSON
{ "phone": [ "123", "456", "789"] }
then PHP's json_decode should handle it without problems.
You can try this code to see it's actually working and use it to detect where something goes wrong:
// original JSON to send from the client
$jsonString = '{ "phone": [ "123", "456", "789"] }';
// build a query string with the JSON to send
$queryString = "?" . http_build_query(array("phone" => $jsonString));
echo "Query string to send is: " . $queryString . PHP_EOL;
// PHP side: this is not a real HTTP GET request, but to pretend we have
// got some data in, we'll use the same query string, parse it, and store it
// in $params
$incoming = parse_url($queryString, PHP_URL_QUERY);
parse_str($incoming, $params);
// now print contents of "phone" parameter
echo "URL parameter phone contains " . $params["phone"] . PHP_EOL;
// JSON-decode the "phone" parameter
var_dump(json_decode($params["phone"], true));
This should print:
Query string to send is: ?phone=%7B+%22phone%22%3A+%5B+%22123%22%2C+%22456%22%2C+%22789%22%5D+%7D
URL parameter phone contains { "phone": [ "123", "456", "789"] }
array(1) {
'phone' =>
array(3) {
[0] =>
string(3) "123"
[1] =>
string(3) "456"
[2] =>
string(3) "789"
}
}
which shows the JSON decodes to a proper PHP array. An array of strings, to be precise, and not numbers as requested. Turning the strings into numbers in PHP will be easy to do, but maybe you could also make sure on the call site that you send numbers and not strings.
If your original code does not work, I guess the incoming data is either no properly encoded JSON or there is some magic escaping going on (magic quotes hell, should be turned off in today's PHP, but could be a reason for garbled script input).
To make sure your JSON data is not truncated and to also save you from potential URL-encoding issues, I also suggest sending the JSON via HTTP POST, not HTTP GET.
The result of the call to the api server is a json file, which begins with this string:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":[{"packWidth":250,"itemNo"
How do I remove the part that I do not care?
that is, this
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":
The complete result is:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result": [{"packWidth":250,"itemNo":"1203945","groupItemNo":"1203945","status":1,"categoryId":105096,"packType":"Color Box","barcode":"6922833439687","modelLabel":"Color","packQty":24,"packInclude":"USB Cable, User Manual, USB Charger, Earphone, 1pcs Li-Battery, LCD Protector, Leather Case, Plastic Case","clearance":false,"id":103928,"packWeight":"12.500","price":"181.2800","packLength":400,"description":"description test","unitWeight":"0.726","packHeight":300}]}}
I use the PHP language
I have to remove the initial part:
{
"result": "success"
, "data": {"total":16080,"pageCount":161,"result":
and the final:
}}
If you want to use part of a JSON to populate a CSV file, then parse the json using json_decode method and access the necessary information.
Try something like this:
var jsonObject = json_decode(myJson);
var interestingPart = jsonObject.data.result;
You can now access the data in an Object manner. Or if you want to get a json back from it, then use:
var interestingJson = json_encode(interestingPart);
Not tested, but it should work
preg_replace("/^.*?:(?=\w*\[) | (\w*}\w*}\w*$)/", "", $str);
Edit: i wrote this before I knew of json_decode, you should really use the json functions like suggested in fazovskys answer.
how do i get this json data in android
this data is in localhost. I must fetch this data using URL and display in listview in android.Can any one help in coding plz
[
{
"id":"111114",
"name":"Prandar"
},
{
"id":"111115",
"name":"Catmilkend"
},
{
"id":"111110",
"name":"Allan"
},
{
"id":"111111",
"name":"Aircornal"
},
{
"id":"111112",
"name":"Allaxander"
},
{
"id":"111113",
"name":"AppleMacro"
}
]
This is a very common need, but involves several independent steps which could easily be their own StackOverflow question.
1) in a file named info.php you will create the JSON string to return to requests:
<?php
// this may come from a database
$info = array ('id' => '101',
'name'=> 'bill'
)
echo json_encode($info); // returns {"id":'101',"name": "bill"}
?>
2) Send a http GET request to myserver.com/info.php and capture the string response.
http://w3mentor.com/learn/java/android-development/android-http-services/example-of-http-get-request-using-httpclient-in-android/
3) Then parse the JSON into objects or dictionary array with a JSON framework.
http://www.jondev.net/articles/Android_JSON_Parser_Example
4) Use a ListView in Android to display it.
http://developer.android.com/resources/tutorials/views/hello-listview.html