Posting JSON and parsing it with php://input is not working - javascript

I want to create an object by sending a json to my webserver and parsing the information.
My javascript looks like this:
import { HTTP } from '#ionic-native/http/ngx';
....
constructor(private http: HTTP){}
...
// combining and sending the information below
createMediaObject(): Observable<any> {
var url = `${ApiServerUrl}/add_mo`;
url = encodeURI(url);
var convertedData = {
type: "Feature",
geometry: {
type: "Point",
coordinates: [Number(this.mediaObjectForm.value.lng).toString(), Number(this.mediaObjectForm.value.lat).toString()]
},
properties: {
icon: this.mediaObjectForm.value.icon.toString(),
tags: this.mediaObjectForm.value.tags.toString(),
topic: this.mediaObjectForm.value.topic.toString(),
title: this.mediaObjectForm.value.name.toString(),
description: this.mediaObjectForm.value.description.toString(),
rotation: this.rotation.toString(),
media: this.mediaObjectForm.value.contents.toString()
}
};
return from(this.http.post(url, convertedData, {})).pipe(map(res => res.data));
}
Now I want to parse the informatik in php using the solution from this post get POSTed JSON Array in php:
$params = json_decode(file_get_contents("php://input"), true);
echo json_encode(array("status" => empty($params)));
try {
// get posted data
echo $params["type"];
if (isset($params["properties"]["topic"])) {
$object->topic = $params["properties"]["topic"];
echo $object->topic;
}
However:
echo json_encode(array("status" => empty($params)));
Output: {"status" : "true"} -> that means that something went wrong and params is empty
same with
echo $object->topic;
Output: null
Is there a problem in the frontend or backend?
Do I need to change something inside of my configs?

Related

fill datatable from php and javascript

Thanks everyone solved by using JSON.parse(xhttp.responseText);
hello i trying to fill up datatable from a php file the data is generator from database then use echo json
and handle the response from javascript here is the php file
<?php
global $wpdb;
$db_list = $wpdb->get_results("SELECT dbtest.FName, dbtest.SName FROM dbtest");
echo json_encode($db_list);
exit;
?>
and here is how i trying to handle the data in javascript
<script>
const xhttp = new XMLHttpRequest()
xhttp.open("GET", "datatabletest.php")
xhttp.send()
http.onload = function() {
var response = xhttp.responseText;
console.log(response);
//from here problem start
$('#example').DataTable({
"data": response,
"columns": [
{ "data": "FName" },
{ "data": "SName" }
]
});
}
</script>
but it alert error DataTables warning: table id=example - Requested unknown parameter 'FName' for row 0, column 0.
it looks like the data from response is null but in console it showing as
[{"FName":"test","SName":"test2"}]
so i have tried to copy this line from console and add it into a var like
var jsdata = [{"FName":"test","SName":"test2"}];
//then use
$('#example').DataTable({
"data": jsdata,
"columns": [
{ "data": "FName" },
{ "data": "SName" }
]
});
}
and that worked so why it not working from the response what is missing to make it work like that

Suitescript RESTlet data get Error Empty JSON string

I have issue using POST Function, I want to transform Transfer Order to Item Receipt, But when I tried to execute the script, it failed with error "org.mozilla.javascript.EcmaError: SyntaxError: Empty JSON string (INVOCATION_WRAPPER$sys#24".
Anyone can help me about my issue ?
Here is my Suitescript Code :
function postData (receiptItem) {
doValidation([receiptItem.recordtype], ['recordtype'], 'POST');
if (receiptItem.recordtype == 'transferorder') {
var recordId = [];
var recStr = [];
var objRecord = record.transform({
fromType: record.Type.TRANSFER_ORDER,
fromId: 131, // transfer Order internalid
toType: record.Type.ITEM_RECEIPT,
defaultValues: {
customform: '433'}
});
var itemReceiptId = objRecord.save({
enableSourcing: false,
ignoreMandatoryField: false
});
recordId.push(itemReceiptId)
log.debug({
"title": "[success] recordId: ",
"details": recordId
});
var recLoad = record.load({
type: receiptItem.recordtype,
id: recordId.getValue('internalid')
});
recStr.push({
use_form: recLoad.getText('customform'),
tran_id: recLoad.getValue('tranid'),
tran_date: recLoad.getValue('trandate'),
tran_from: recLoad.getValue('transferlocation'),
tran_to: recLoad.getValue('location'),
tran_ord_id: recLoad.getvalue('createdfrom'),
tran_memo: recLoad.getValue('memo')
});
log.debug({
"title": "recStr",
"details": recStr
});
return recStr;
}
}
return {
post: postData
};
});
It's a syntax error, very likely some misplaced bracket.
Make sure you are posting valid JSON and that the content type is set on your request
You must send data as JSON. if empty or no data then send {} at least in POST as ContentType is Application/JSON. ECMA Standard. The error message clearly states that "Empty JSON string".
Then try this in Postman tool.

Is it possible to update js file using php command?

I have script.js file. and it has following array
script.js
'COntent': function() {
var contentFacts = {
blocks: {
'block1': {
name: 'yleow',
title: 'H2',
type: 'content'
}
}
};
}
},
I tried like this in my php , but it did not work :(
$lines = file($path.'/script.js');
$lines[64] = "'block2': {name: 'yleow',title: 'H2',type: 'content'}"
file_put_contents($path.'/script.js', implode($lines));
I want to add another element call block2 for this array. How can i update my script.js file function using php?
Is it possible using file_put_contents? please advice
JavaScript is a very poor substitute for a database or any other structured data format. In this case even more because you are trying to inject content into source code.
What you probably want is some form of structured data outside of your code for example a JSON file or an SQLite database.
PHP does support parsing from and serializing to JSON:
json_decode
json_encode
Possible solution
Put the contentFacts into a seperate JSON file
{
"blocks": {
"block1": {
name: 'yleow',
title: 'H2',
type: 'content'
}
}
}
Manipulate JSON with PHP
$json = file($path.'/blocks.json');
$blocks = json_decode($json, true);
$blocks['block2'] = array(
'name' => 'blue',
'title' => 'h3',
'type' => 'content'
);
Write back to JSON file
$adapted_json = json_encode($blocks);
file_put_contents($path.'/blocks.json');
Now you need to get this into your JavaScript part, I assume on the client. You can do this by requesting it from the server:
const contentPromise = fetch('/path/to/blocks.json');
contentPromise.then((blocks) => {
// Do something with those blocks. (render them to the page?)
});

retrieve an array in php after passing from angular js

I have an array like this
$scope.kk = [
{ name:'Computer Architecture', price:65 },
{ name:'Advanced Composite Materials', price:45 },
{ name:'Stategies Unplugged', price:43 },
{ name:'Teaching Science', price:50 },
{ name:'Challenging Times', price:22 }];
I have passed this array to my controller through webapi like this
var req1= {
method: 'POST',
url: apiPoint.url + 'sin.php',
headers: {
'Content-Type': 'application/json'
},
params :{
"fulldet[]" : $scope.kk
}
$http(req1).then(function (response) {
if (response.data.status) {
alert(JSON.stringify(response.data));
}
}
And in my controller i need to extract this array
I have used foreach statement like this
$result['ppp'] = $fulldet;
foreach($fulldet as $e){
$result['lm']=$e['name'];
}
But am getting ILLEGAL STRING OFFSET 'name'
Please help me.
For my reference i hv printed my array back after the response from controller. I get it like this
{"ppp":["
{\" name\":\"Computer Architecture\", \"price\":65 },
{\" name\":\"Advanced Composite Materials\", \"price\":45 },
{ \"name\":\"Stategies Unplugged\", \"price\":43 },
{\" name\":\"Teaching Science\", \"price\":50 },
{\" name\":\"Challenging Times\", \"price\":22 }"]}
Before trying to iterate over array apply json_decode to it.
$result['ppp'] = json_decode($fulldet, true);
foreach($fulldet as $e){
$result['lm']=$e['name'];
}
as i see now, your problem is when you try to get the data on the server side (sorry , for previous answer).
the parameter that you pass inside the request should be string not array
so you change this:
params :{
"fulldet[]" : $scope.kk
}
to this:
params :{
"fulldet" : $scope.kk
}
try to get your POST data like this:
$results = json_decode(file_get_contents('php://input),true);
foreach($results as $item){
echo $item['name'];
}

Unexpected token syntax error using Ext.data.ScriptTagProxy

Ok I am using the Ext.data.ScriptTagProxy to pull json data from a remote server (which I happen to manage) and am receiving this error: Uncaught SyntaxError: Unexpected token :
I am querying a database with the following PHP page and encoding the results in json:
<?php
header('Content-Type: text/javascript');
$db_name = "foo"; // The name of the database being used.
$db = mysql_connect("localhost", "foo user", "foo pass") or die ("Unable to connect to database.");
mysql_select_db("$db_name", $db);
echo '{"recipes": ';
$query = "SELECT * FROM wp_recipes";
$result=mysql_query($query);
$_ResultSet = array();
while ($row = mysql_fetch_assoc($result)) {
$_ResultSet[] = $row;
}
echo json_encode($_ResultSet);
echo "}";
?>
And here is the code I am using to make the Cross domain call using Sencha:
var store = new Ext.data.Store({
model : 'Recipes',
sorters: [
{property: 'recipeName', direction: 'ASC'}
],
getGroupString : function(record) {
return record.get('recipeName')[0];
},
proxy: new Ext.data.ScriptTagProxy({
url: 'http://myvisalusdiet.com/app/json_output2.php'
}),
reader: new Ext.data.JsonReader({
root: 'recipes',
idProperty : 'recipeName',
id: 'id'
}),
autoLoad : true
});
Anybody see anything unusual which would case the syntax error? Thanks in advance for your help!
For a start, I am having a hard time validating your json. Currently its wrapped in (parenthesis) rather than {brackets}
([{"id":"3","ingredients2":"4 oz. (1\/2 cup orange juice)","ingredients3"
...
,"ingredients":"6 oz. skim milk","website":null}]);
and not sure that javascript is too helpful, firebug for example would like to see "application/json" != "application/javascript" for laying out data. this doesnt impact parsing/linting though.

Categories

Resources