Displaying HTML content in a field - html

I'm getting a JSON response from the server. Inside that JSON string I have HTML content which I need to display in a field. How do I do this?

Is this what you need? What kind of field?
If it's a div or p
var yourContent = "";
$(".selector").html(yourContent);
If it's textbox use
$(".selector").val(yourContent);
That's of course if you using jQuery

If the JSON result is say:
({
name: 'John'
})
We grab it and operate on it like so:
$.getJSON("http://yourjsonresource",
function(data){
$('h1#foo').text( data.name );
}
);

Related

How to display long string data from JSON as a list wise using react typescript

How to display long string data from JSON as a list wise if Description string is too long. How do i split or format description Using react and typescript .
I have below JSON data:
"options": [
{
"perkType": "GIFT_CARD",
"tierRewardId": "ff592a61-3e64-474e-a3e5-cb7c14cc73e1",
"perkDescription": "**Important details about the Perk:**\n* Perks are random additional items. These are not earned, but extra items given to customers outside of the spend levels.\n* See Terms and Conditions for exclusions and additional information.\n* [Terms & Conditions](www.xyz.net/TermsandConditions)",
},
{
"tierRewardId": "0aa6b029-3179-41dd-8726-78ca7e4bfe18",
"perkType": "TOOL_RENTAL",
"perkDescription": "**Important details about the Mik Perk:**\n* Mik Perks are random additional items. These are not earned, but extra items given to customers outside of the spend levels.\n* See Terms and Conditions for exclusions and additional information.\n* [Terms & Conditions](www.xyz.net/TermsandConditions)"
}
],
already i filter the data :
const optionGift = this.state.currentData.item.tierPerks[0].options.filter(
(list) => list.perkType === 'GIFT_CARD');
const optionGiftCard= optionGift.map((value)=> value );
const OptionRental = this.state.currentData.item.tierPerks[0].options.filter(
(list) => list.perkType === 'TOOL_RENTAL',);
const OptionRentalTool= OptionRental.map((value)=> value );
component tsx code :
<div> <ul className="YourPerkOption__modelParagraph">
<li>{props.optionGiftCard[0].perkDescription}</li></ul></div>
I am trying to display a list wise data into below format
if anybody can help please .
Custom Code
If I am understanding this correctly, the first line of the perkDescription is the title (**Important details about the Mik Perk:**) and the subsequent lines are bullet points. We need to break up the string into multiple string segments and then render them to the DOM through JSX. Let's make that into it's own reusable component.
The only prop that we need is the string text.
interface PerkDescriptionProps {
text: string;
}
Our component breaks that text into an array of lines with the string.Prototype.split() method. We store the first element of the array to a variable title and the rest of the lines to another variable bullets using spread syntax. We then loop through the bullets array and put each one inside of a li element.
export const PerkDescription = ({ text }: PerkDescriptionProps) => {
const lines = text.split("\n");
const [title, ...bullets] = lines;
return (
<div className="perkDescription">
<div className="perkDescriptionTitle">{title}</div>
<ul className="perkDescriptionList">
{bullets.map((line, i) => (
<li key={i}>{line}</li>
))}
</ul>
</div>
);
};
You would call it like this:
<PerkDescription text={optionGiftCard[0].perkDescription} />
But I think you should create a Perk component that uses this PerkDescription!
I am not dealing with the asterisks here so you'll still see them in the HTML output. Are you using some some of package to parse markdown syntax?
Markdown Parsing
Your JSON is using a standardized markdown syntax to denote the list. There are already packages out there which can handle the bulleted list as well as turning the link into an a element and adding the bold styling to the title.
Using react-markdown, all you need to do is put your text inside of a ReactMarkdown component.
import ReactMarkdown from 'react-markdown'
<ReactMarkdown>{optionGiftCard[0].perkDescription}</ReactMarkdown>
You could use a RegEx to split perkDescription into an array and then map that array.

Vuejs changes order of json_encoded array, when decodes it back from props in vuejs component

Php:
$json_string = "{
"26":{"blabla":123,"group_id":1,"from":"27.08.2018","to":"02.09.2018"},
"25":{"blabla":124,"group_id":1,"from":"20.08.2018","to":"26.08.2018"},
"24":{"blabla":125,"group_id":1,"from":"20.08.2018","to":"26.08.2018"}
}"
my.blade.php template:
<my-component :records={{ $json_string }}></my-component>
MyComponent.vue:
export default {
props: ['records'],
...
mounted: function () {
console.log(this.records);
}
Output is:
{__ob__: Observer}
24:(...)
25:(...)
26:(...)
And when I use v-for, records in my table in wrong order (like in console.log output).
What I am doing wrong?
EDIT:
I figured out 1 thing:
When I do json_encode on collection where indexes are from 0 till x, than json string is: [{some data}, {some data}]
But if I do ->get()->keyBy('id') (laravel) and than json_encode, json string is:
{ "26":{some data}, "25":{some data}, "24":{some data} }
Then how I understood, issue is in different outer brackets.
In Javascript keys of objects have no order. If you need a specific order then use arrays.
Here is documentation for keyBy Laravel method: https://laravel.com/docs/5.6/collections#method-keyby
I wanted to have ids for rows data to fast and easy access without iterating over all rows and check if there is somewhere key Id which is equals with my particular Id.
Solution: not to use keyBy method in Laravel and pass json string to Vue component like following [{some data}, {some data}] (as I described in my Question Edit section) - this will remain array order as it used to be.
I found this short and elegant way how to do this, instead of writing js function by myself:
Its find() method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Example:
let row = records.find( record => record.id === idToFind );

How to extract "sunny" from below represented format?

var email = req.body.emailId;
connection.query('SELECT name FROM fun WHERE email = "' + email +'" ',function(err, result,fields) {
console.log(result);
});
The console displays "result" in the below format:
[{name:'sunny'}]
Can someone tell me how to display"sunny"?
Sunny should be accessible with the following code
alert(result[0].name); //sunny!
As you can see, the JS object displayed is an array with one element, which is an object with one key (name).
So you simply index the array to the first value result[0] and then fetch that element's name value result[0].name.

Split JSON data when comma is found

I want to separate and put data into array. Here's my AJAX code if it succeeded.
success : function(data){
alert (data);
$('#status').append("<p>Tax Declaration: "+data[0]
+ "<br/>Barangay: "+data[1]+"</p>"
);
},
sample out put is 08-09-0001-00047,BILAY. I want them to be separated.
If you have a string that is comma separated and you want to create an array of the items in the list, use split() like this:
var values = data.split(",");
$('#status').append(
"<p>Tax Declaration: "+values[0] + "<br/>Barangay: "+values[1]+"</p>"
);
As #Andy Jones mentioned, use .split() like so:
success : function(data){
data = data.split(/\s*,\s*/g);
$('#status').append("<p>Tax Declaration: "+data[0]
+ "<br/>Barangay: "+data[1]+"</p>"
);
},

Dynamic ng-Grid with JSON data in angularJS?

I want to make a dynamic ng-grid , which adjusts its columns according to the key values in my JSON object. JSON object is fetched from an api. the problem I am facing is defining columns at runtime i.e The columns are not available at design time but will only be available only at runtime. I want to have something like :
http://plnkr.co/edit/q1Ye10OsIn9NOJmrICyD?p=preview
So that, I have as many columns as keys in my Json object. API's can vary so I need to make a grid which adjusts its columns.
My plunker is not working, but I hope it gives you idea, what I am trying to do.
Unless I'm misunderstanding what you want, you don't need to mess with columnDefines. Just having this:
faculty.controller('facultycontroller', function facultycontroller($scope, $http, $window){
$scope.facdata = [];
$scope.gridOptions = {
data: 'facdata'
};
$http.get("http://mtapi.azurewebsites.net/api/institute").then(function (result) {
$scope.facdata = result.data;
console.log($scope.facdata[0]);
});
});
will create the grid with a column for each key in your json.
Update
If you want to filter out any columns that begin with '$', you can do something like this:
angular.forEach(result.data[0], function(value, key){
if(key.indexOf('$') != 0)
$scope.columnDefines.push({ field: key, displayName: key});
});
Actually, you were close with what you were trying to do. You just need to put the columnDefines variable on $scope, and assign it to the gridOptions using a string, like this:
$scope.columnDefines = [];
$scope.gridOptions = {
data: 'facdata',
columnDefs: 'columnDefines'
};
Plunker
Try attaching your columnDefines variable to the scope ($scope.columnDefines). Then in your options do this:
$scope.gridOptions =
{
data: 'facdata',
columnDefs: 'columnDefines' //Note the quotes
};
This will make ng-grid watch your columnDefs for changes