PolymerJS POST JSON formatting - javascript

I am trying to POST using PolymerJS ajax-forms and I encounter a weird JSON format error. Can someone tell me why the quotes are missing around the keys? The only workaround I can think of is manually constructing the body with the quotes around the keys.
Code Snippet :
How I receive the values (rest are the same with the ids changed):
<div>
<paper-input label="Title" id="course-title" floatingLabel value="{{item.title}}"></paper-input>
</div>
<access-core-ajax
auto = "false"
url="domain/courses"
response="{{response}}"
method="post"
id="postCourse"
contentType="application/json"
headers='{"Accept": "application/json", "Content-Type":"application/json"}',
body = "{{item}}">
<template id="get-response-template" repeat="{{item in response.entries}}">
<p>Errors</p>
</template>
</access-core-ajax>
Polymer('create-new-course-page',{
domReady: function() {
console.log("Log: create-new-courses-page - Looks like we are domReady");
},
created: function() {
console.log("Item initialized");
this.item = {};
this.data={};
},
createNewCourse: function(event) {
console.log("HERE IS BODY", this.item);
this.$.postCourse.go();
}
And the JSON is see on the log:
{
title: "WRU",
// rest of key & values, where the keys are without the ""
}

You need to turn the body into a JSON string first. JSON.stringify can help.
...
createNewCourse: function(e) {
this.$.postCourse.body = JSON.stringify(this.item);
this.$.postCourse.go();
}
You may need to remove the body attribute here. You can also remove that auto attribute since by default it is false.

Related

How to apply json content for html attribute

I am trying to add json object for html arrtibute content but not working.I have tried many ways but I do not know how to set that.if any one know about that please help to resolve this issue.
javascript:
var validatorValue='{
"picker":{
"allow":
{
"message": "Content loram ipsom"
},
"past":
{
"message": "lorem issom"
}
}
}' ;
var daterestrictValue="{'range': {'start': '2019-10-30','end': '2019-12-30'}}";
var myinputValue="{'date':'tomorrow'}";
$("#mydiv").html("<div input="true" validator='+validatorValue+' date-restrict='+daterestrictValue+' my-input='+myinputValue+'></div>");
The main issue with your code (aside from line-breaks in string literals) it the mis-matched quotes in the HTML string you build. However, even after correcting those you will have issues placing serialised JSON within attributes as it too contains double quotes which will break the HTML syntax.
Also note that you're creating non-standard attributes in the HTML you create which may cause unexpected issues in your UI and JS.
An alternative way to approach this is to work with the values as objects (instead of strings). You can use jQuery to set the data of the element using those objects, like this:
var validatorValue = { "picker": { "allow": { "message": "Content loram ipsom" }, "past": { "message": "lorem issom" } } }
var daterestrictValue = { 'range': { 'start': '2019-10-30', 'end': '2019-12-30' } }
var myinputValue = { 'date': 'tomorrow' };
var $newDiv = $('<div data-input="true">Click me</div>').appendTo('#mydiv');
$newDiv.data({
"validator": validatorValue,
"date-restrict": daterestrictValue,
"my-input": myinputValue
});
// for testing
$('#mydiv div').on('click', function() {
console.log($(this).data('validator'));
console.log($(this).data('date-restrict'));
console.log($(this).data('my-input'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="mydiv"></div>
this code save object in html element.
good luck
var validatorValue="{ 'picker':{'allow':{'message': 'Content loram ipsom'},'past':{'message': 'lorem issom'}}}";
var daterestrictValue="{'range': {'start': '2019-10-30','end': '2019-12-30'}}";
var myinputValue="{'date':'tomorrow'}";
$("#mydiv").html(`
<div input='true' validator="${validatorValue}" date-restrict="${daterestrictValue}" my-input="${myinputValue}">ggg</div>`);

React : how to prevent escaping in data-attribute

I have a JSON that looks like this { "id":"xyz", "height":1024, "width":1024 } which I would like to have in a data attribute like :
<div data-command='{"id":"xyz","height":1024,"width":1024}'></div>
but when I use react it escapes the string as shown below :
<div data-command='{"id":"xyz","height":1024,"width":1024}'></div>
I use this code to generate the element
React.createElement("div",
{ "data-command" : JSON.stringify({ "id":"xyz", "height":1024, "width":1024 }), null)
does anyone know how I can get the JSON without the " escaping?
If it's not possible how can I transform it back in javascript so I can use JSON.parse after?
The 'dangerouslySetInnerHTML' attribute is precisely used for scenarios like this.
createMarkup() {
return {__html: `<div data-command='{"id":"xyz","height":1024,"width":1024}'></div>`};
}
render() {
return (
<div dangerouslySetInnerHTML={this.createMarkup()}>
</div>
);
}

Vue.js - Trouble displaying results from API call in component

Experimenting with Vue.js, trying to display results from a Wikipedia API call in a component using the v-for directive, but something is not working on the back end and I don't know what it is.
Link to the jsFiddle
HTML
<div id="app">
<input type="text" v-model="searchTerm" v-on:keyup="getResults">
<searchResult
v-for="item in results"
v-bind:result="item"
v-bind:key="item.key"
></searchResult>
</div>
Javascript
new Vue({
el: '#app',
data: {
api: "https://en.wikipedia.org/w/api.php?",
searchTerm: 'Ron',
searchDataString: "action=opensearch&format=json&origin=*&uselang=user&errorformat=html&search="+this.searchTerm+"&namespace=0%7C4&limit=20&profile=fuzzy",
searchCall: this.api+""+this.searchDataString,
results: []
},
methods: {
getResults() {
this.searchCall = this.api+"action=opensearch&format=json&origin=*&uselang=user&errorformat=html&search="+this.searchTerm+"&namespace=0%7C4&limit=20&profile=fuzzy";
//console.log( this.searchCall );
axios.post( this.searchCall )
.then(response => { this.processResults(response.data) });
},
processResults(data) {
//console.log( data );
for(var i = 0; i < data[1].length; i++) {
var resultItem = { key:i, link:data[3][i], name:data[1], description:data[2][i] };
this.results.push(resultItem);
console.log(resultItem);
}
}
}
});
Vue.component( "searchResult", {
props:['result'],
template: "<a target='_blank' href='{{ result.link }}'><div class='search-result'><h3>{{ result.name }}</h3><p>{{ result.description }}</p><div></a>"
});
The two issues on my mind are
the error message that shows in the console when typing input, and
that the array of results is creating empty objects instead of passing the data
When I look at the array in the console, all it shows are getters and setters. I'm new to this, so maybe that's what it's supposed to be doing.
I'm so close to getting this working, but I'm at my wits end, help is much appreciated.
The problem with your code is that html tags aren't case sensitive so naming a component searchResult causes issues. If you need to use searchResult, you'll have to use <search-result> in your template. I find it better just to avoid the problem altogether and give components lower-case names. Here are docs about the issue: https://v2.vuejs.org/v2/guide/components.html#Component-Naming-Conventions
You mentioned "the error message that shows in the console when typing input". I didn't get any errors copying and pasting your code (other than forgetting to include axios). What error are you getting?

How can I access array element value in json

I'm not able to access _sValues in my html page, however i can able to console.log the interested _sValues array element in console.
JSON
[
{
"_this":{
"_isEvent":false,
"_sNames":[
"name",
"tag",
"notes",
"input",
"type",
"action"
],
"_sValues":[
"Testing01",
"#13",
"1504013826",
"No details",
"cType",
"NA"
],
"_cName":"namesList",
"_dName":"TEST",
"_id":"12345",
}
}
]
HTML
<th class="col-md-5 col-xs-5" data-field="_this._sValues[1]" data-sortable="true">S-VALUES</th>
I would like to see #13 displayed on the page instead i don't see any values or console error. However i can display all values by doing _this.sValues
SCRIPT
var data;
$(function () {
$.getJSON("http://localhost:8080/services/webapi/getAllData", function(json){
data = json;
$('#table').bootstrapTable({
data: data
});
});
});
DEV TOOL
data[0]._this._sValues[1]
"#13"
In your case,
i assume you only have one row.
$(".col-md-5").attr("data-field",data[0]._this._sValues[1]);
It will inject the data to html.
If you have multi row, you can use for loop.
I believe you have a silent error. It has to do with the trailing comma in your data object.
"_id":"12345",
// should be
"_id":"12345"
That's all I noticed. I Courbet wrong but I know trailing commas mess with some browsers.

Meteor template isn't rendering properly

I'm building a notifications page, where the user can see which posts have comments, and I want to display the date of each post, but it's not working.
Here is the code:
<template name="notification">
<li>Someone commented your post, {{postDate}} </li>
</template>
Template.notification.helpers({
notificationPostPath: function() {
return Router.routes.PostPage.path({_id: this.postId});
},
post: function () {
return Post.findOne({_id: this.postId});
},
postDate: function() {
return moment(post.submitted).format('dddd, MMMM Do');
}
});
The console prints this: Exception from Deps recompute: ReferenceError: post is not defined.
Thanks in advance
I assume the error is being flagged on the following line:
return moment(post.submitted).format('dddd, MMMM Do');
Note that you can't refer to helpers from within other helpers like that (and anyway, post is a function) - you need too add another line at the start of the postDate helper like this:
var post = Post.findOne({_id: this.postId});

Categories

Resources