how to convert unicode and display in browser? reactjs - javascript

I am creating a messages page where admin and client can send and receive messages and I am getting some characters which show up, and another developer tells me it's unicode.
something like this
\u2019hey
or this
m\u0159i\u0165 sroun\u011br tro\u0161a hro\u010d ti\u010d s\u00fds\u016f v diplych o zrutr\u00fd. Zlyzli crest\u016fstbukl\u00e1 slokab zlecou, a nij \u0159uk\u00fd tiv. Nij dratl\u00e1h. Tref\u00fd zraditi tin\u011bgle. \u017el\u00edzlod mrytl\u00e9 n\u011bj vosk n\u011bmu z chlyv\u011bt oskev ston div\u011bm. Nivp\u00e1du\u0161 obozr\u016f sre\u0165n\u011bch k\u0159oufl\u00fd a pi\u0148 syb\u0159otru slou\u0161\u00ed. Bliti m\u0159opidtisly vuvle obu ji\u0161 p\u0159a\u010d m\u00e1n\u011b chapupotid \u017eredi hl\u00fdt zrouskod. Vl\u016fbu lkyd k mlozrat, brsk mled\u0159ej koudyzrozr\u00e1 \u0161k\u00fdnid k t\u011bviz. Z kluz studip bruh\u0159ou s d\u00e1tiv\u011b ti\u017elo dikre\u010d. Zu veplev \u0148\u00e1mesk \u010fo\u010d k otil. T\u0159a\u010d i tipo vl\u00e9\u0165o\u0165 k su\u010f kl\u00fdpru \u0161udi\u0148\u010fa
so, how do I convert it to a format more suitable to display on the browser?? using reactjs
these could be icons or anything . not sure.
Here's an example array of what I am getting from server.
I am putting it into an array and then looping through it to display like this
msgContent = arr.map((item,index)=>{
let len = arr.length-1;
if(len ===index){
return <span key={index+100} className={styles.textMsg}>{item}</span>
}else{
return <span key={index+100} className={styles.textMsg}>{item}<br/></span>
}
})
and it still shows up garbled.
could you tell me where am I going wrong here?

Different ways of displaying HTML entities are listed in the documentation. The examples you have in your question are unicode numbers corresponding to the entity, which works perfectly fine as strings in JSX, so if you just want to display them properly, you don't have to change it at all.
Example
function App() {
return <div> {"\u2019hey"} </div>;
}

Related

How to get the ChoiceField value using javascript

First of all sorry for my bad english i am french !
So i have a little problem. I use the django built-in class ChoiceField in my form :
class LogForm(forms.Form):
FormData = (('1', 'Code',), ('2', 'Normal',), ('3', 'Hexa',))
choixFormData = forms.ChoiceField(label=' Forme des donnees ', choices=FormData)
liaison = (('1', 'RS232_1_Port1',), ('2', 'RS232_1_Port2',), ('3', 'RS232_1_Port3',), ('4', 'RS232_1_Port4',),
('5', 'RS422_1_Port1',), ('6', 'RS422_1_Port2',), ('7', 'RS422_1_Port3',), ('8', 'RS422_1_Port4',),
('9', 'RS422_2_Port1',), ('10', 'RS422_2_Port2',), ('11', 'RS422_2_Port3',), ('12', 'RS422_2_Port4',),
('13', 'VoieNumAna',), ('14', 'CAN1',), ('15', '1553',))
choixLiaison = forms.ChoiceField(label='Liaison', choices=liaison)
Data = forms.CharField(required=False, label=' Data ', max_length=100, widget=forms.Textarea)
And i also use the Django Channels in order to implement websockets in my app.
The thing is, i want to be able to render the form thanks to the view ( this is working fine ) and then i want to get the value of the selected choice ( once the the form is rendered ) using javascript.
I tried this :
document.querySelector('#id_Start').onclick = function(e) {
const messageInputDom = document.querySelector('#id_choixLiaison');
const message = messageInputDom.value;
chatSocket.send(JSON.stringify({
'message': message
}));
messageInputDom.value = '';
}
I am very new to javascript and i dont understand the reason why this is not working.
I want to be able to get the value of the selected choice field in a string.
Do not hesitate to tell me if the question is badly asked or if you need more details.
Thank you !

Javascript: Parsing xml to get matched tag value within node

I am a beginner level javascripter, and have the following problem. I am adding javascript functionality to an assessment form.
The user will choose an item from a dropdown giving me a value which I can grab an stuff in a variable. (so var appetite=2 for example).
I then have an XML document loaded into the DOM as a variable.
What I need to do is to search the XML for the value within matched nodes and grab a paired value to give me a score.
My XML looks like this:-
<root Patient_ID="1333" Current_User="Iain Cowden" Current_Date="05/02/2021" Current_Time="20:15">
<SQLQuery elementNameInResults="BMI" recordCount="1">select top 1 BMI ,<br/>case when BMI between 20 and 24.9 then 1<br/>when BMI between 25 and 29.9 then 2<br/>when BMI >=30 then 3<br/>when BMI<20 then 0 end as BMI_Score,<br/>case when gv.Gender_ID=2 then 2 <br/>when gv. Gender_ID=3 then 1 end as Gender_Score,<br/>case when dbo.GetAge(Date_Of_Birth,Estimated_Year_Of_Birth,Date_Of_Death) <=49 then 1<br/>when dbo.GetAge(Date_Of_Birth,Estimated_Year_Of_Birth,Date_Of_Death) between 50 and 64 then 2<br/>when dbo.GetAge(Date_Of_Birth,Estimated_Year_Of_Birth,Date_Of_Death) between 65 and 74 then 3<br/>when dbo.GetAge(Date_Of_Birth,Estimated_Year_Of_Birth,Date_Of_Death) between 75 and 80 then 4<br/>when dbo.GetAge(Date_Of_Birth,Estimated_Year_Of_Birth,Date_Of_Death) >80 then 5 end as Age_Score,<br/>dbo.GetAge(Date_Of_Birth,Estimated_Year_Of_Birth,Date_Of_Death) as Age,<br/>gv.Gender_Desc as Gender<br/><br/>from tblCHTHealthNoteMeasure nm<br/>join tblpatient p on p.Patient_ID=nm.Patient_ID<br/>join tblgendervalues gv on p.gender_id=gv.gender_id<br/>where nm.Patient_ID=#patientID order by Health_Note_Date desc<SqlParameter name="#patientID" value="1333" type=""></SqlParameter></SQLQuery>
<BMI>
<BMI>35.2</BMI>
<BMI_Score>3</BMI_Score>
<Gender_Score>1</Gender_Score>
<Age_Score>4</Age_Score>
<Age>80</Age>
<Gender>Male</Gender>
</BMI>
<SQLQuery elementNameInResults="WLAppetiteID" recordCount="4">select UDP_WLAppetite_ID as WLAppetiteID, External_Code1 as WLAppetite from udpWLAppetiteValues where #patientID=#patientID<SqlParameter name="#patientID" value="1333" type=""></SqlParameter></SQLQuery>
<WLAppetiteID>
<WLAppetiteID>0</WLAppetiteID>
<WLAppetite>0</WLAppetite>
</WLAppetiteID>
<WLAppetiteID>
<WLAppetiteID>1</WLAppetiteID>
<WLAppetite>2</WLAppetite>
</WLAppetiteID>
<WLAppetiteID>
<WLAppetiteID>2</WLAppetiteID>
<WLAppetite>3</WLAppetite>
</WLAppetiteID>
<WLAppetiteID>
<WLAppetiteID>3</WLAppetiteID>
<WLAppetite>5</WLAppetite>
</WLAppetiteID>
I know how to use xmlDoc.getElementsByTagName("Gender_Score")[0].textContent for example to return the Gender score for the first SQLQuery Nodeset above.
However I can't quite figure out how I can look through the second SQL Query nodeset to find the pair where WLAppetiteID = 2 and then get the value of WLAppetite.
I can't really figure out where to start. GetElementsByTagName just gets me an html collection of all the WLAppetiteID tags regardless of NodeLevel.
I did try using IndexOf or includes on that, but that doesn't seem to be valid.
Any help or pointers deeply appreciated.
The xml in your question is not well formed (for example, it's missing a closing <root> tag, but what you are looking for can be done this way:
text = `[your xml, fixed]`
let parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
path = ".//WLAppetiteID[.=2]/following-sibling::WLAppetite"
target = xmlDoc.evaluate(path, xmlDoc, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
console.log(target.snapshotItem(0).textContent);
Output is 3.

How to bind a dictionary with an HTML <p> tag in angular?

So I know nothing about angularJS and I haven't found any good explanation on how to bind a dictionary with an html tag so that every change in the dictionary produces a change in the number inside the <p> tag. For example if I have multiple dictionaries inside an array (one for each player)
var players = [{bambu:0, clouds:0, fruits:0}, {bambu:0, clouds:0, fruits:0} , {bambu:0, clouds:0, fruits:0}]
I want to display the number associated with bambu in a <p> tag
<p id="player_0_bambu" class="number_of_cards"> </p>
I want to change it dinamically like angular does.
I tried to do a
while (true){
for (var r=0; r< num_players;r++){
for (var c=0; c< colores.length;c++){
$("#player_"+r+"_"+colores[c]).html(players[r][colores[c]])
}
}
}
but a while true just crashes javascript, so I turned to angular but I find it difficult to understand.
Thank you for your help!
Not sure why angular would be an option but judging by your description you just loop through the players array and use the values from the object at hand to query for <p/> tags.
var players = [{ bambu:0, clouds:0, fruits:0 }, {bambu:0, clouds:0, fruits:0 } , { bambu:0, clouds:0, fruits:0} ]
players.forEach(player => {
Object.keys(player).forEach(key => {
const val = player[key];
document.querySelector(`#player_${val}_${key}`).innerHTML = val;
});
});

Laravel - JS [ajax] Var must be constant

i will be happy if someone know how to do this and why i m getting error , i would like to pass "var size" inside route() method inside forelse is it somehow passible ?
whot it do ?
based on radio box ( if size M and L are avaible there will be 2 radioboxes ), then if user click on add to card it gets Value of radio box for example ( 6 ) = L them pass it to ajax route
Error :
Use of undefined constant size - assumed 'size' (View: C:\xampp\htdocs\EcSc\resources\views\shop\home.blade.php)
JS :
<script>
var CartCount = {{ Session::has("cart") ? Session::get("cart")->totalQty : "0" }} ;
var size;
#forelse($products as $productsjs)
$("#product-{{$productsjs->id}}").click(function () {
var radios{{$productsjs->id}} = document.getElementsByName('radio-{{$productsjs->id}}');
for (var i = 0, length = radios{{$productsjs->id}}.length; i < length; i++) {
if (radios{{$productsjs->id}}[i].checked) {
// do whatever you want with the checked radio
size = radios{{$productsjs->id}}[i].value;
// only one radio can be logically checked, don't check the rest
break;
}
}
$.ajax({
type: "get",
url: "{{route("product.addToCartAjax", $productsjs->id, size)}}", // insert product with specific size into session
success: function () {
CartCount++;
$("#shoppingCartCounter").html(CartCount);
console.log("Produkt bol pridani");
console.log("Velkost produktu je : " + size); // size contain value of checked radio box
}
})
});
#empty
#endforelse
</script>
You can't print the javascript variable in PHP. Think of {{ }} as <?php ?>. If you just insert it in there, it may look like <?php echo size; ?> which won't work, as obviously size will look like a constant here, which of course is undefined (your error).
Instead, you need to declare the variable in php. However, since you're doing this after run time, there's no way that you're going to be able to assign a PHP variable after the page has been rendered. So what are your alternatives?
1 - Construct the route manually: (recommended, easiest)
url: '/products/' + {{$productsjs->id}} + '/add-to-cart-ajax/' + size
2 - Use a client side route generator for Laravel, such as La Route (harder, but more dynamic and reusable)
laroute.route('product.{id}.addToCartAjax.{size}', {id: '{{$productsjs->id}}', size: size});
3 - Other generic solutions such as generating the route ahead of time and dynamically modifying it with javascript (ugly, non-portable)

How to do a Pug for loop with AJAX?

I am working on a Tinder clone web project for school using Node.js, Express, and Pug that needs to return potential matches with a priority on either distance from the current user or similar interests shared with the current user. When the user first enters their page of potential matches I have the site automatically show the user the best possible matches based on a distance of 5km from their current position. I am sending to the page I render an Array of matches called users and a size of that array called userslen that I pulled from my database in my node file. I then proceed to show the potential matches on the page using this pug for loop:
div(class='container', id='searchResults') <!-- SEARCH RESULTS -->
div(class='row')
- for (var i = 0; i < userslen; i++) {
div(class='col-lg-4 col-md-6 col-sm-12 col-xs-12 usertop')
div(class='row')
div(class='col-lg-12 col-md-12')
a(href='/users/' + users[i].username)
h1=users[i].username
- if (users[i].liked == true) {
span(id='youlikeglyph', class="glyphicon glyphicon-ok")
- } else if (users[i].disliked == true) {
span(id='youdislikeglyph', class="glyphicon glyphicon-remove")
- } else {
- }
div(class='row')
div(class='col-lg-12 col-md-12')
img(id='viewerphoto1', class='userpagephoto', src='/static/uploads/' + users[i].filename)
div(class='row')
- if (users[i].liked == false && users[i].disliked == false) {
div(class='btn-group')
button(id='dislike' + i, class='btn btn-danger btn-lg')
|Dislike
button(id='like' + i, class='btn btn-success btn-lg')
| Like
- } else if (users[i].liked == false && users[i].disliked == true) {
button(id='like' + i, class='btn btn-success btn-lg')
|Like
- } else if (users[i].liked == true && users[i].disliked == false) {
button(id='dislike' + i, class='btn btn-danger btn-lg')
|Dislike
- } else {
- }
div(class='row')
div(class='col-lg-4 col-md-4')
h5="Distance"
h4=users[i].distance + "km"
div(class='col-lg-4 col-md-4')
h5="Same Tags"
h4=users[i].cTags
div(class='col-lg-4 col-md-4')
h5="Popularity"
h4=users[i].popularity
- }
There are two buttons at the top of my page (not shown in the above code) that allow a user to choose to search based on distance or based on tags with a min and max distance/tags-in-common input. When they click on the button of their choice with the min max they have entered I send the data through AJAX to a post that then returns a new array of potential matches based on this new data. Is there a way to make the same for loop I have in the above code but using jQuery once my AJAX response is a success? If there is, what is the best way to go about it? Thank you in advance for your help!
You cannot go back to Jade/Pug once you're on the client. Jade is a templating engine that works on Node. Once you're on the client, it doesn't exist anymore.
You'll need to just loop over your HTML in jQuery, and won't be able to use Jade for this.
Another option is to use one of the client side templating frameworks like Underscore templates/Handlebars/Moustache JS etc.
Using these, you can handle the looping much more elegantly than you can using jQuery, but of course, that really is a call you should take, because this would mean additional payload over the wire.
With one of the templating frameworks, you can define your template in Jade and then reuse it for your iterations

Categories