Get JSON data from external form in codeigniter - php

I have an external web form which posts data to my controller URL. The data is sent in a JSON string.
What I need to do is get the individual values in the JSON string and add them to my database. However I'm having some trouble getting the posted values and decoding them.
Here is the code which I tried - any help would be much appreciated Thanks.
public function index() {
$this->load->view('lead');
$form_data = array(
'firstname' => json_decode($this->input->post('first_name')),
'lastname' =>json_decode($this->input->post('last_name')),
'number' =>json_decode($this->input->post('phone_number')),
'email' =>json_decode($this->input->post('email')),
'suburb' =>json_decode($this->input->post('suburb')),
'state' =>json_decode($this->input->post('state')),
'enquiry' =>json_decode($this->input->post('enquiry'))
);
// run insert model to write data to db
if ($this->AddLeadModel->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db { //Do something if successful }

Do not json_decode the individual form fields.
You have to json_decode the incoming field with the json instead,
then use the array data to populate the form again.
In easy words: You from fields were stuffed into an array on JS side, then json_encoded for transfer to the server. Now you need to expand the json to get the array back.
// decode the incomning json
// you get an array
$json_array = json_decode($this->input->post('the_form_field_name_of_your_json'));
// now assign the array data to the form
$form_data = array(
'firstname' => $json_array['first_name'],
...
...
);

try this:
$json = file_get_contents('php://input');
$input_data = json_decode($json, TRUE);

Will explain with an example (THIS WORKS):
// Assuming the values you are getting via POST
$first_name = '{"first_name" : "Parag"}';
$last_name = '{"last_name" : "Tyagi"}';
$phone_number = '{"phone_number" : "9999999999"}';
$form_data['firstname'] = json_decode($first_name, TRUE)['first_name'];
$form_data['lastname'] = json_decode($last_name, TRUE)['last_name'];
$form_data['number'] = json_decode($phone_number, TRUE)['phone_number'];
print_r($form_data);
DEMO:
http://3v4l.org/dmIrr
Now check below (THIS WON'T WORK):
// Assuming the values you are getting via POST
$first_name = "{'first_name' : 'Parag'}";
$last_name = "{'last_name' : 'Tyagi'}";
$phone_number = "{'phone_number' : '9999999999'}";
$form_data['firstname'] = json_decode($first_name, TRUE)['first_name'];
$form_data['lastname'] = json_decode($last_name, TRUE)['last_name'];
$form_data['number'] = json_decode($phone_number, TRUE)['phone_number'];
print_r($form_data);
DEMO:
http://3v4l.org/MeJoU
Explanation:
If you pass the JSON in your post to json_decode, it will fail. Valid JSON strings have quoted keys. Hence check your case and see in what format are you getting the JSON (via POST).

Related

PHP Modify JSON file with foreach

I have a json file:
$json='[{"Email":"myemail1#domain.com","Name":"company 1","Tel1":"xx-xx-xx","Adresse":"XXXXXX"},{"Email":"myemail2#domain.com","Name":"Company 2","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}]';
and my forms post data in variable
vars="fname"=>"Ameur","lname"=>"KHIL"
"fname"=>"Marak","lname"=>"Cristo"
and I like to insert in between my json content with variable to get the final json like this:
$result='[{"Email":"myemail1#domain.com","Name":"company 1","vars":{"fname":"Ameur","lname":"KHIL","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}},{"Email":"myemail2#domain.com","Name":"Company 2","vars":{"fname":"Marak","lname":"Cristo","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}}]';
For this purpose you can use json_decode() to parse the JSON-String to a PHP-Object. Then you just set a new value vars to the given form values.
Parsing the JSON-String
$json = json_decode('[{"Email":"myemail1#domain.com","Name":"company 1","Tel1":"xx-xx-xx","Adresse":"XXXXXX"},{"Email":"myemail2#domain.com","Name":"Company 2","Tel1":"xx-xx-xx","Adresse":"XXXXXX"}]');
Adding the new vars value and removing the additional ones. This is just for the first entry but you can do the same for the other entry or even iterate through the array for multiple entries
$json[0]->vars = ["fname" => "Marak", "lname" => "Cristo", "Tel1" => $json[0]->Tel1,"Adresse" => $json[0]->Adresse];
unset($json[0]->Tel1);
unset($json[0]->Adresse);
And getting your result in a JSON-String
$result = json_encode($json);

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

Parse data from webhooks

I am parsing data from webhook using this:
$data = json_decode(file_get_contents('php://input'), true);
So I have array of data in json file. How can I can get all of fields be as variables in json (Like { time: 'now' } be variable $time='now';
PHP has an extract function that will convert array keys into variables. Whether that is a good idea is a totally different question.
$data = json_decode(file_get_contents('php://input'), true)
return arrray expample array('time':'10:00');
you can get variable example
echo $data['time'];
oupt put => 10:00

D3js Multi line graph convert from using CSV file

I am looking to make a multi line graph from this example.
Instead of using data from a CSV file I'm building an array of values from the database:
$token_prices = sw::shared()->prices->getForTokenID($token_id);
$token_prices_array = array();
foreach ($token_prices as $token_price) {
$token_prices_array[] = [
"date" => $token_price['date'],
"close" => $token_price['close']
];
}
$second_token_prices = sw::shared()->prices->getForTokenID(3);
$second_token_prices_array = array();
foreach ($second_token_prices as $second_token_price) {
$second_token_prices_array[] = [
"date" => $second_token_price['date'],
"close" => $second_token_price['close']
];
}
$all = array_merge($second_token_prices_array, $token_prices_array);
foreach ($all as $datapoint) {
$result[$datapoint['date']] []= $datapoint['close'];
}
Data output:
{"15-Jun-18":["8.4","0.14559"],"16-Jun-18":["8.36","0.147207"],"17-Jun-18":["8.42","0.13422"],"18-Jun-18":["8.71","0.146177"],"19-Jun-18":["8.62","0.138188"],"20-Jun-18":["8.45","0.128201"],
My issue is with plugging the data from the database in:
var tokendata = <?php echo json_encode($result) ?>;
data = tokendata;
data.forEach(function(d) {
d.date = parseTime(d.date);
d.close = +d.close;
d.open = +d.open;
});
I get an issue here "data.forEach is not a function"...
How can I fix this to use the data from the database?
Here is the Fiddle
It looks like you are embedding the results of the query php page as a JSON string -- if you want to iterate over that data as an array, you will have to parse it back into a Javascript object first.
I'm assuming that the first code snippet is running on a different server, and so the $result array is not directly available to your javascript code -- is this why you are trying to set a variable to the encoded return value? If so, it's not the best way to pull data into your page's script, but this may work for you:
var data = JSON.parse('<?php echo json_encode($result)?>');
or even:
var data = eval(<?php echo json_encode($result)?>);
Both methods assume that your result is returned as a valid json string, since there is no error checking or try/catch logic. I honestly don't know what the output of the json_encode() method looks like, so if you still can't get it working, please update your post with an example of the returned string.

how to get post data from array input fields in getParams() in SLIM PHP

i am having a form with some array input fields like name[],age[],gender[] etc.
and i am trying to access the post data in slim php with a function using
$name = $request->getParam('name');
but iam not getting any data. Any kind of help will be appreciated. Thanks in advance.
If you want to pass an array of objects you can achieve the same by passing the value in JSON format.
For example:
My Sample JSON format is as below.
{
"news_title": "Title",
"news_description": "news_description",
"news_date": "03-12-2017",
"image_list": [
{
"imagedata": "data",
"fileName": "Imags12.png"
},
{
"imagedata": "data",
"fileName": "Imags11.png"
}
]
}
You can read this JSON data in slim as described below.
$app->post('/create_news_json', function () use ($app) {
$json = $app->request->getBody();
$data = json_decode($json, true); // parse the JSON into an assoc. array
$news_title=$data['news_title']; // to retrieve value from news_title
$news_description=$data['news_description']; // to retrieve value from news_description
$news_date = date_format(date_create($data['news_date']),"Y-m-d"); // to
retrieve value from news_date and convert the date into Y-m-d format
$news_ImageList=$data['image_list']; //read image_list array
$arr_length=count($data['image_list']);//calculate the length of the array.
// trace each elements in image_list array as follows.
for($i=0;$i<count($news_ImageList);$i++)
{
$imagedata = $news_ImageList[$i]['imagedata']; //read image_list[].imagedata element
$filename = $news_ImageList[$i]['fileName']; //read image_list[].fileName element
}
});
In postman you can pass the JSON object as row data in the format of application/json in body section.
By using this concept any kind of complex data structures can be passed into the slim as JSON object.It can accomplish most of you data passing goals.
It looks like you have the general idea, but after looking at the documentation. It seems like you need to employ slim's helpers for the post data. This is the example that the documentation displays in order to retrieve the values of title and description. As mentioned below, the filter_var() is not necessary but it is highly recommended and good practice in order to add an extra level of protection by removing any special characters that might do harm.
$app->post('/ticket/new', function (Request $request, Response $response) {
$data = $request->getParsedBody();
$ticket_data = [];
$ticket_data['title'] = filter_var($data['title'], FILTER_SANITIZE_STRING);
$ticket_data['description'] = filter_var($data['description'], FILTER_SANITIZE_STRING);
// ...
https://www.slimframework.com/docs/tutorial/first-app.html, This is the link for the example if you would like to read more about it.
$names = $request->getParam('name');
$genders = $request->getParam('gender');
$ages = $request->getParam('age');
$persons = array();
for($i=0;$i<count($names);$i++){
$arr['name'] = $names[$i];
$arr['gender'] = $genders[$i];
$arr['age'] = $ages[$i];
array_push($persons,$arr);
}
You can accesss form data sent by html form with
$name=$req->getParsedBodyParam("name");

Categories