I'm just starting out in Angular and I'm trying to update my JSON file with a PHP script. The script updates it with the right keys but null values. I'd really appreciate some help.
Here's my code:
<?php
$object_data = array(
'capital' => $_POST['in1'],
'country' => $_POST['in2'],
'continent' => $_POST['in3'],
'image' => $_POST['in4']
);
$capitals = file_get_contents('capitals.json');
$capital_data = json_decode($capitals);
array_push($capital_data,$object_data);
$jsondata = json_encode($capital_data,JSON_PRETTY_PRINT);
file_put_contents('capitals.json',$jsondata);
?>
And here's my JSON file:
[
{
"capital": "Ottawa",
"country": "Canada",
"continent": "North America",
"image": "https:\/\/upload.wikimedia.org\/wikipedia\/commons\/2\/22\/Parliament-Ottawa.jpg"
},
{
"capital": "Oslo",
"country": "Norway",
"continent": "Europe",
"image": "https:\/\/upload.wikimedia.org\/wikipedia\/commons\/thumb\/b\/bd\/Downtown_Oslo_Norway_skyline.png\/800px-Downtown_Oslo_Norway_skyline.png"
},
{
"capital": "Auckland",
"country": "New Zealand",
"continent": "Oceania",
"image": "https:\/\/upload.wikimedia.org\/wikipedia\/commons\/6\/6e\/Auckland_City_from_Mt_Victoria%2C_Devonport_-_Flickr_-_111_Emergency_%281%29.jpg"
}
]
Lastly, here's my post request in Angular:
$http.post('capitalData.php',
{"capital":input1.val(),"country":input2.val(),
"continent":input3.val(),"image":input4.val()}).success(function(){
alert("Added!");
});
Edit: Updated the post request to specify which data I'm sending but it still returns nulls.
Related
I am trying to add a customer(Podio item) to my Podio app. This customer is being added programmatically from within a php application. There are several fields present on the customer: Name, Address, Email, Title, Phone Number, and an array of Tags. When a tag is added the color changes to highlight it.
In previous iterations I have been successful adding a different tag(newsletter_subscribed) using the ID of the tag value that I want highlighted. Now when I try to add another tag(hospital, clinic, or urgent_care) it is throwing a PodioBadRequestError. The error cited is that the ID being used is and invalid type(integer).
I got the values of the tag ID's by looking at the JSON returned when an existing customer created manually within my Podio customer application. When I look at the ID fields in the JSON they are most definitely integers, I have tried strings as well. Everything I try throws the 400 Bad Request on the ID that I am trying to add.
I cannot for the life of me figure out why it is throwing the error when I add the tag ID's.
Below is the way that the application is put together:
This is the code that builds and sends the request:
public function addToPodio()
{
$address = $this->Address . ", " .
$this->Address2 . ", " .
$this->City . ", " .
$this->State . " " .
$this->Zip;
$item = [
'fields' => [
'name' => $this->PrimaryContactFirstName,
'last-name' => $this->PrimaryContactLastName,
'email-address' => ['type' => 'work', 'value' => $this->PrimaryContactEmail],
'phone-number' => ['type' => 'work', 'value' => $this->PrimaryContactPhone],
'address' => $address,
'organization' => [$this->CompanyName],
'tags-2' => []
],
];
if ($this->Newsletter && defined('PODIO_NEWSLETTER_TAG_ID')){
$item['fields']['tags-2'][] = PODIO_NEWSLETTER_TAG_ID;
}
if($this->OrganizationType && defined('PODIO_ORGANIZATION_TYPE_ID')){
if($this->OrganizationType == "Clinic"){
$item['fields']['tags-2'][] = PODIO_ORGANIZATION_TYPE_CLINIC_TAG_ID;
}
else if($this->OrganizationType == "Hospital"){
$item['fields']['tags-2'][] = PODIO_ORGANIZATION_TYPE_HOSPITAL_TAG_ID;
}
try {
//This is where the request is being made
$customer = PodioItem::create(PODIO_CUSTOMER_APP_ID, $item);
$this->PodioId = $customer->item_id;
$this->write();
} catch (Exception $e) {
error_log('We encountered an error adding your item to Podio' . $e);
return 'An error occurred while updating Podio. Please try again. If the error...';
}
This is the PHP $item that is being passed to the request that gets sent to the Podio API:
Array
(
[fields] => Array
(
[name] => Joe
[last-name] => Test
[phone-number] => Array
(
[type] => work
[value] => 8675309
)
[address] => 123 Main Road, , East Test, NY 12345
[organization] => Array
(
[0] => Another Test
)
[tags-2] => Array
(
[0] => 16
[1] => 96
)
)
)
This is the config file with the all of the constants, secrets tokens and ID's needed to connect to the Podio API, authenticate and all of that stuff. Obfuscated Example below:
define('PODIO_CUSTOMER_APP_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CUSTOMER_APP_TOKEN', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CLIENT_SECRET', 'xxxxx-obfuscated-xxxxx');
define('PODIO_CLIENT_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_ORGANIZATION_TYPE_ID', 'xxxxx-obfuscated-xxxx');
define('PODIO_NEWSLETTER_TAG_ID', 'xxxxx-obfuscated-xxxxx');
define('PODIO_ORGANIZATION_TYPE_CLINIC_TAG_ID', 'xxxxx-obfuscated-xxxxx');
Podio::setup(PODIO_CLIENT_ID, PODIO_CLIENT_SECRET, [
'session_manager' => Injector::inst()->get(PodioSession::class),
'curl_options' => array(),
]);
Below is the JSON that I used to get the values of the ID's. I got this from a postman request to the API. The basic form of the request without all of the authentication present looked like:
podio.com/MY_PODIO_ACCOUNT_NAME/app/APPLICATION_ID/item/ITEM_ID
Please note: I removed many of the main fields like Address and Organization for brevity's sake, so it won't match completely the PHP request object above.
{
"id": 0000,
"item_id": 00000,
"revision": 0,
"app": null,
"app_item_id": 00000,
"app_item_id_formatted": "PODIO_Field_ID:00000",
"external_id": null,
"title": "TEST ITEM",
"fields": [
{
"id": 0000,
"field_id": 0000,
"type": "text",
"external_id": "name",
"label": "First Name",
"values": [
{
"value": "Joe"
}
],
"config": {
"settings": {
"format": "plain",
"size": "small"
},
"mapping": "contact_name",
"label": "First Name"
},
"humanized_value": "Joe"
},
{
"id": 0000,
"field_id": 0000,
"type": "text",
"external_id": "last-name",
"label": "Last Name",
"values": [
{
"value": "<p>Test<br /></p>"
}
],
"config": {
"settings": {
"format": "html",
"size": "large"
},
"mapping": null,
"label": "Last Name"
},
"humanized_value": "Test"
},
{
"id": 0000,
"field_id": 0000,
"type": "phone",
"external_id": "phone-number",
"label": "Phone Number",
"values": [
{
"type": "work",
"value": "867-5309"
}
],
"config": {
"settings": {
"call_link_scheme": "callto",
"possible_types": [
"mobile",
"work",
"home",
"main",
"work_fax",
"private_fax",
"other"
]
},
"mapping": "contact_phone",
"label": "Phone Number"
},
"humanized_value": "8675309"
},
{
"id": 11111,
"field_id": 11111,
"type": "category",
"external_id": "tags-2",
"label": "Tags",
"values": [
{
"value": {
"status": "active",
"text": "Clinic",
"id": 16,
"color": "DCEBD8"
}
},
{
"value": {
"status": "active",
"text": "Newlsetter_subscribed",
"id": 96,
"color": "DCEBD8"
}
}
],
"config": {
"settings": {
"multiple": true,
"options": [
{
"status": "active",
"text": "Mktng:test1/2020",
"id": 150,
"color": "DCEBD8"
},
{
"status": "active",
"text": "Mktng:Test2/2020",
"id": 3,
"color": "DCEBD8"
},
{
"status": "active",
"text": "SampleTest",
"id": 48,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Test Center",
"id": 139,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Sample Center",
"id": 99,
"color": "DCEBD8"
},
{
"status": "deleted",
"text": "Testing Center",
"id": 140,
"color": "DCEBD8"
}
],
"display": "inline"
},
"mapping": null,
"label": "Tags"
},
"humanized_value": "Clinic; Newsletter;"
}
this JSON continues for pages and pages, I only included the relevant fields for my question.
It looks like the error is being thrown because of the organization value, not the tags value.
For a category field, an array of integer indices is correct.
[tags-2] => [ 16, 96 ]
For an app field, you need to provide an array of integer item ID's.
[organization] => [ 12345 ]
But your code above is sending an array of strings:
[organization] => [ "Another Test" ]
That won't work.
I know that it's a common question, but I have a different problem.
When I retrieve a Json response from PHP, it throws this alert warning and don't load the data into the datatable.
When I load the generated Json (retrieved from PHP) directly from file, the datatable loads the data correctly.
I have the following jquery configuration for my datatable:
$( document ).ready(function() {
$('#example').dataTable({
"language": {
"url": "//cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json"
},
"bProcessing": true,
"sAjaxSource": "response.php",
"aoColumns": [
{ mData: 'id' } ,
{ mData: 'name' },
{ mData: 'description' }
//{ mData: 'img', render: getImg },
]
});
});
The generated json from php (that works if loaded directly from file):
{
"sEcho": 1,
"iTotalRecords": 10,
"iTotalDisplayRecords": 10,
"aaData": [{
"id": "1",
"name": "Salsa estilo Casino",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "2",
"name": "Salsa estilo Son",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "3",
"name": "Salsa LA",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "4",
"name": "Salsa NY",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "5",
"name": "Bachata",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "6",
"name": "Reggaeton",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "7",
"name": "Chachacha",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "8",
"name": "Rumba",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "9",
"name": "Pachanga",
"description": "Descri\u00e7\u00e3o ..."
}, {
"id": "10",
"name": "Ritmos tradicionais cubanos",
"description": "Descri\u00e7\u00e3o ..."
}]
}
My PHP response.php file:
<?php
// my database classe with CRUDed POJOs.
include_once '../admin/db.php';
// That was from a sample code that worked fine.
$data = array(
array('Name'=>'Descrição ...', 'Empid'=>11, 'Salary'=>101, 'img' => '../img/lais.jpg'),
array('Name'=>'alam', 'Empid'=>1, 'Salary'=>102, 'img' => '../img/lais.jpg'),
array('Name'=>'phpflow', 'Empid'=>21, 'Salary'=>103, 'img' => '../img/lais.jpg')
);
/* Query the database and retrive in $data2[0] the total number of rows
and $data2[1] an array of arrays with the following format (as described above):
array(
array('id' => '1', 'name' => 'name', 'description' => 'Desc ...'),
...
)
*/
$data2 = Turma::fetchAllAssoc();
$results = array(
"sEcho" => 1,
"iTotalRecords" => 10,
"iTotalDisplayRecords" => 10,
"aaData"=>$data2[1]);
header('Content-Type: application/json');
echo json_encode($results);
?>
What am I doing wrong? It seems a bug form me.
Solved my problem.
In PHP, the response.php was returning only the json content that was shwon in the browser.
The error was: there was some html commented content that seems hidden in `include_once '../admin/db.php';, even the commented html tags.
When I added the line header('Content-Type: application/json'); everything that seems missing was shown in the browser.
Erased everything, even commented html tags to output (echo) only json_encode($results);. Then, everything worked smoothy.
I want JSON object as follows in that personal, address and itm have sequence of json object.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact":"1111111"
"address": [
{
"line1": "abc",
"city": "abc",
"itm": [
{
"num": 1,
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0,
}
}
],
"status": "Y"
}
]
}
]
}
But I am getting result as follows in that I want json array at address and itm_details.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact": "1111111",
"address": {
"line1": "abc",
"city": "abc",
"itm": {
"inum": "1",
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0
}
},
"status": "Y"
}
}
]
}
My PHP Code is as follow:
In that I am creating simple array and after that array inside array but during encoding to json it's not showing sequence of json object.
$a=array();
$a["id"]="1";
$a["state"]="12";
$a["personal"]=array();
$a["personal"][]=array(
"name"=>"abc",
"contact"=>"1111111",
"address"=>array(
"line1"=>"abc",
"city"=>"abc",
"itm"=>array(
"inum"=>"1",
"itm_detatils"=>array(
"itemname"=>"bag",
"rate"=>1000,
"discount"=>0,
),
),
"status"=>"Y",
),
);
echo json_encode($a);
Thanks in advance.
Add one more array
//...
"address" => array(
array(
"line1"=>"abc",
"city"=>"abc",
// ...
),
)
I have some data like this
"name": "abc",
"adr": "bcd",
"partners": {
"101": {
"name": "xyz.com",
"prices": {
"1001": {
"description": "Single Room",
"amount": 125,
"from": "2012-10-12",
"to": "2012-10-13"
},
"1002": {
"description": "Double Room",
"amount": 139,
"from": "2012-10-12",
"to": "2012-10-13"
}
}
Now, I have to write a json with all this data and use it as a data source.
How can I do it ?
The data you posted is not valid JSON. It misses some surrounding and ending brackets.
Ok, let's fix that... and save it as data.json:
{
"name": "abc",
"adr": "bcd",
"partners": {
"101": {
"name": "xyz.com",
"prices": {
"1001": {
"description": "SingleRoom",
"amount": 125,
"from": "2012-10-12",
"to": "2012-10-13"
},
"1002": {
"description": "DoubleRoom",
"amount": 139,
"from": "2012-10-12",
"to": "2012-10-13"
}
}
}
}
}
To access the JSON with PHP you can simply load the file and convert the JSON to an array.
<?php
$jsonFile = "data.json"
$json = file_get_contents($jsonFile);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
A PHP Script to create a file containing this data as json
// the data you need
$phpData = [
"name" => "abc",
"adr" => "bcd",
"partners" => [
"101" => [
"name" => "xyz.com",
"prices" => [
"1001" => [
"description" => "Single Room",
"amount" => 125,
"from" => "2012-10-12",
"to" => "2012-10-13",
],
"1002" => [
"description" => "Double Room",
"amount" => 139,
"from" => "2012-10-12",
"to" => "2012-10-13",
]
]
]
]
];
// json_encode() that data to a string
$jsonData = json_encode($phpData);
// write that string to your file
file_put_contents('myJsonFile.json', $jsonData);
And to use it as a datasource
$myData = json_decode(
file_get_contents('myJsonFile.json')
);
My contents of MongoDB(when i used find()) is like this:
{
"_id": ObjectId("50072b17b4a6de3b11000001"),
"addresses": [
{
"_id": ObjectId("50072b17b4a6de3b11000004"),
"address1": "770 27th Ave",
"address2": null,
"city": "San Mateo",
"country": "United States",
"country_code": "US",
"name": "home",
"primary": true,
"state": "California",
"zip": "94403"
}
],
"biography": null,
"category_ids": [],
"department": null,
"emails": [
{
"_id": ObjectId("50072b17b4a6de3b11000003"),
"_type": "Email",
"name": "work",
"email": "alan#altimetergroup.com"
}
]
}
What I need to do is I need to update this MongoDB with additional datas's. For that I need to get the values in php as an array and insert that array in to this collection. How to get the values for these specified fields as an array in php and how to insert those in php??
$array = $this->collection->findOne(array('_id' => MONGO_ID));
//Update things
$this->collection->update(array('_id' => $array['_id']), $array);
MONGO_ID in my example should represent the '_id' MongoDB automatically assigns. Make sure it is sent as an Object, and not as a string.
If you want to add another entry, you add an entry like so:
$this->collection->insert($array_of_data, array('safe' => true));
For insert:
$id = new MongoId();
$test->insert(array('t' => 'test', 'email' => array('_id' => $id, 'email' => 'ccc#ccc.com')));
And the result:
{ "_id" : ObjectId("5088cba86527044a31000001"), "t" : "test", "email" : { "_id" : ObjectId("5088cba86527044a31000000"), "email" : "ccc#ccc.com" } }
It works :)