Post Json array in url - php

Is it possible to pass JSON in a URL?
For example, I have an array:
data = {
"name": "test",
"user_id": 1
}
I want to pass it in to a URL like:
http://example.com/jsonArray

You should better use POST to pass such type of data, but, absolutely you could make a :
$str = serialize(json_decode($data, true));
And then pass you $str in url.

You can't send the JSON array directly, but you can prepare it in a way that allows it to be sent to your API. You turn your JSON into a string and encode it so it will be properly formatted for a GET.
// your JSON data
var data = '{"name":"Homer Simpson","status":"Suspended","disciplinary-dates":["2018-01-2","2018-02-14","2018-03-17"]}' ;
// take your JSON, turn it into a string and then encode it
var urlParams = encodeURIComponent(JSON.stringify(data)) ;
// your URL adding your JSON data as the value
var url = 'http://example.com/?params=' + urlParams ;
On the PHP side you will decode
// note: this code does not have any error checking - you should add it
// get your params
$params = $_GET['params'] ;
// decode the string
$decodedParams = urldecode($params) ;
// turn your string into an array
$wasJSONAsArray = json_decode($decodedParams, true) ;
// turn your string into a std object
$wasJSONAsStdObj = json_decode($decodedParams) ;

Related

How can convert query string in laravel to json

I have a problem here, I want to change the query string that I received to the json form as follows
{"id":"89"}
here I try to use json_encode but the one it produces is
""?id=89""
here is my code
$coba = str_replace($request->url(), '',$request->fullUrl());
if (empty($coba)) {
$url = "{}";
} else {
$url = $coba;
}
$json_body = json_encode($url);
there I also want to change if there is no query string then the result is {}
This should do it for you for both conditions:
json_encode($request->query(), JSON_FORCE_OBJECT);
PHP Manual - JSON Functions - json_encode
Laravel 5.8 Docs - Requests - Retrieving Input - Retrieving Input From The Query String query
//get Parameters
$array = [
'id' => 20,
'name' => 'john',
];
//getting the current url from Request
$baseUrl = $request->url();
//we are encoding the array because
//u said that the get parms in json format
//so that ...
$json = json_encode($array);
//now building the query based on the data
//from json by decoding it
$query = (http_build_query(json_decode($json)));
//at the end of the url you need '?' mark so...
$url = \Illuminate\Support\Str::finish($baseUrl,'?');
//now Merging it
$fullUrl = $url.$query;
dump($fullUrl);
For any issues kindly comment

i need help on parsing json url on php

Here is the json content:
{
"success":true,
"data":"{\"campaign_name\":\"helloworld\",\"download_link\":\"https:\\\/\\\/google.com\\\/accesskey\\\/getfile\\\/m-spqn-e61-2aef2575a0b5250354f2b0fda033e703?token=HUSYjdC5jyJskXUHiKn13l1A1BaAjH2R&dcma=5ecceb0522bcd0db\",\"link\":\"http:\\\/\\\/www.lol.com\\\/remove\\\/remove.php\"}",
"message":null
}
I'm looking to get the value of download_link. How can I do that?
This is what I tried:
<?php
$jsndata = {"success":true,"data":"{\"campaign_name\":\"helloworld\",\"download_link\":\"https:\\\/\\\/google.com\\\/accesskey\\\/getfile\\\/m-spqn-e61-2aef2575a0b5250354f2b0fda033e703?token=HUSYjdC5jyJskXUHiKn13l1A1BaAjH2R&dcma=5ecceb0522bcd0db\",\"link\":\"http:\\\/\\\/www.lol.com\\\/remove\\\/remove.php\"}","message":null};
$jsn = json_decode($jsndata,true);
$temperatureMin = $jsn['data'][6]['download_link'];
echo $temperatureMin;
?>
You have a json object containing another serialized json object.
Decode the first object, get the second serialized object and decode that:
$jsndata = '{
"success":true,
"data":"{\"campaign_name\":\"helloworld\",\"download_link\":\"https:\\\/\\\/google.com\\\/accesskey\\\/getfile\\\/m-spqn-e61-2aef2575a0b5250354f2b0fda033e703?token=HUSYjdC5jyJskXUHiKn13l1A1BaAjH2R&dcma=5ecceb0522bcd0db\",\"link\":\"http:\\\/\\\/www.lol.com\\\/remove\\\/remove.php\"}",
"message":null
}';
// Decode the main json object
$jsn = json_decode($jsndata,true);
// Since 'data' is another serialized object, you need to decode that as well:
$data = json_decode($jsn['data'], true);
// Now you can access the contents of 'data'
echo $data['download_link'];
Demo: https://3v4l.org/1PcQp
You need:
- quotes around your JSON
- to remove the quotes around the inner object
$jsndata = '{"success":true,"data":{\"campaign_name\":\"helloworld\",\"download_link\":\"https:\\\/\\\/google.com\\\/accesskey\\\/getfile\\\/m-spqn-e61-2aef2575a0b5250354f2b0fda033e703?token=HUSYjdC5jyJskXUHiKn13l1A1BaAjH2R&dcma=5ecceb0522bcd0db\",\"link\":\"http:\\\/\\\/www.lol.com\\\/remove\\\/remove.php\"},"message":null}' ;
And you need to remove the [6] from your array access:
$temperatureMin = $jsn['data']['download_link'];

Postgresql query result PHP encode converted array to string

I have an SQL query that converts result to json.
SELECT 'FeatureCollection' As type, array_to_json(array_agg(f)) As features FROM (
SELECT 'Feature' As type,
ST_AsGeoJSON(geom)::json As geometry,
row_to_json((name, category)) As properties
FROM my_geometry_table
) As f ;
I am using this query in PHP script.
$result = pg_query($connection, $queryString);
$resultArray = pg_fetch_all($result);
echo json_encode($resultArray[0]);
My php result is like this: (array is double-quote )
{
type: "FeatureCollection",
features: "[]"
}
But it should be like this:
{
type: "FeatureCollection",
features: []
}
It's important to remember that JSON is a way of representing data inside a string. PHP does not know that something is JSON, only that it's a string.
You need to first decode the result from Postgres (which is a JSON string) so that you have a PHP array. Then you can encode that PHP array back to JSON:
$result = pg_query($connection, $queryString);
$resultArray = pg_fetch_all($result);
// $resultArray[0]['features'] is a string of JSON data from the DB
// For example, let's say it's '[1,2,3]'
// To you, this is obviously JSON: it looks like it,
// and you know you asked for that column to be JSON in the SQL.
// But PHP has no idea; it just sees a 7-character long string;
// so we need to tell it to decode that string:
$decoded_features_array = json_decode($resultArray[0]['features']);
// $decoded_features_array is now a PHP array containing 1, 2, and 3
// Obviously, you can just write that value straight back into the result
$resultArray[0]['features'] = json_decode($resultArray[0]['features']);
// Now the 'features' field of the result is an actual array,
// not a string, so we can do with it whatever we'd do with any other array
// That includes encoding it to send somewhere else - in this case, as JSON:
$json_result = json_encode($resultArray[0]);
// $json_result is now a string with all the fields
// and our PHP array gets encoded as a JSON array as we wanted:
// e.g. '{"type": "FeatureCollection", "features": [1,2,3]}'

javascript objects to json string to php array -> POST

Hey guys i really need help with this. i pass this json object to php..
var x = {};
x.xt = {};
x.xt.id = id;
x.xt.to = foo;
somearray.push(x);
convert object to json:
$.toJSON(x);
json string:
[{"x":{"xt":"9","to":"2"}}]
them i post this:
$.post(
"temp/sop.php",
{ xa: somearray},
function(data){
console.log("response - "+ data);
});
server side:
$xtj = $_POST["xa"];
$encodedArray = array_map(utf8_encode, $xtj);
$asnk = json_decode($encodedArray);
This returns:
string(4) "null"
and this:
$asnk = json_encode($xtj);
returns:
null
the data base it is set to:
UTF8
also when i test if it is an array, comes back true..
any idea how to solve this? thanks
also server side:
$xtj = $_POST["xa"];
$asnk = json_decode($xtj);
this returns:
NULL
$.toJSON(x) does not do the conversion in-place; it returns the JSON, and you're just discarding it. You need this instead:
$.post(
"temp/sop.php",
{ xa: $.toJSON(somearray) },
// ...
});
Then, on the PHP side, you won't want array_map as it's not going to be an array until you decode the JSON:
$xtj = $_POST["xa"];
$encodedArray = utf8_encode($xtj); // I'm not sure you need this, by the way.
$asnk = json_decode($encodedArray);
try using
if(get_magic_quotes_gpc()) $xtj = stripslashes($xtj);
to lose the excessive escaping before trying to decode.
What you are doing is you are converting to json string in JS ($.toJSON()).
And then in PHP you are again trying to convert to json string (json_encode()).
And you are using array_map() on something that is not an array but a string. (Try echo $_POST["xa"]; to see the contents of it.)

How to pass an array of objects from javascript to PHP

If I have, in javascript, something like:
entriesObj1 = new Object();
entriesObj1.entryId = "abc";
entriesObj1.mediaType = 2;
entriesObj2 = new Object();
entriesObj2.entryId = "def";
entriesObj2.mediaType = 1;
var entries = new Array();
entries[0] = entriesObj1;
entries[1] = entriesObj2;
What is the best method to pass it to php through an HTTP POST?
I've tried a jQuery plugin to convert the array to JSON. I've tried to create multiple hidden fields named "entries[]", each one with the JSON string. Somehow, I can't seem to decode my data with PHP's json_decode.
EDIT:
I tried changing the JSON plugin used to the one #Michal indicated and the results I get are the same:
Javascript
[
{"disciplina":"sdfsdfsdfsd","titulo":"sdfsdfsdf","componentes":"Bloco Completo"},
{"disciplina":"sdfsdfsdfsd","titulo":"sdfsdfsdf","componentes":"Bloco Completo"}
]
PHP Vardump:
string(756) "
[
{\"disciplina\":\"sdfsdfsdfsd\",\"titulo\":\"sdfsdfsdf\",\"componentes\":\"Bloco Completo\"},
{\"disciplina\":\"sdfsdfsdfsd\",\"titulo\":\"sdfsdfsdf\",\"componentes\":\"Bloco Completo\"}
]
"
When I use PHP's json_decode, I get NULL.
var_dump(json_decode($_REQUEST['entries']));
Output:
NULL
You need to convert JSON to a string (use JSON stringifier (https://github.com/douglascrockford/JSON-js) and POST the string (as a field value) to the PHP script which does json_decode()
Concat it using some characters like _ or %% then pass it to PHP.
In PHP file:
$ar = array();
$ar = explode('special_char',string pass from js);
echo "pre";print_r($ar);
echo "/pre";
well, the trouble seemed to be with the quotes that were being passed in the post, so i just replaced the quotes with open strings to my $_REQUEST.

Categories