I am struggling with a problem using axios.
Vue file:
<script>
export default {
name: 'npcs-list',
data () {
return {
data: '',
index: '',
dialogues: '',
input: {
npc_name: '',
},
npc_id: '',
npc_name: '',
npc_start_dialogues:'',
dialogues: [],
fields: [{
name: 'id',
callback: 'stringToInt'
},
{
name: 'name'
},
{
name: 'start_dialog'
},
{
name: 'actions', // <----
title: 'Akcje',
titleClass: 'center aligned',
dataClass: 'center aligned'
}
],
css: {
pagination: {
wrapperClass: 'pagination pull-right',
activeClass: 'btn-primary',
disabledClass: 'disabled',
pageClass: 'btn btn-border',
linkClass: 'btn btn-border',
icons: {
first: '',
prev: '',
next: '',
last: ''
}
}
}
}
},
components: {
Vuetable,
VuetablePagination,
VuetablePaginationInfo
},
methods: {
insertNPC () {
const data = this
if (this.input.npc_name != '' && this.npc_start_dialogues != '') {
axios.post('http://localhost/test/Quests/endpoints/insert.npc.php', {
npc_name: 'dupa',
npc_startdialog: 'dupa2'
})
.then((response) => {
data.status = response.data
})
.catch(function (error) {
console.log(error)
})
if (data.status == '1') {
alert('Działa!')
} else {
alert('Taki tag już istnieje!')
}
} else {
alert('Brak wystarczającej ilości danych')
}
},
showModal(data) {
this.$refs.myModalRef.show()
this.data = data,
this.npc_id = data.id,
this.npc_name = data.name,
this.npc_start_dialogues = data.start_dialog.split(";")
},
hideModal () {
this.$refs.myModalRef.hide()
},
onHidden (evt){
this.npc_id = '',
this.npc_name = '',
this.npc_start_dialogues = ''
},
log (data) {
console.log(data)
},
editDialogue (data) {
this.$router.push({
name: 'editDialogues',
params: {
id: data
}
})
},
editOption (data) {
this.$router.push({
name: 'editOptions',
params: {
id: data
}
})
},
}
</script>
PHP endpoint:
<?php
header('Content-Type: text/html');
include_once '../Checkers/CheckIfNPCExists.php';
include_once '../Inserts/InsertNPC.php';
$requestBody = file_get_contents('php://input');
$data = json_decode($requestBody);
$status = new CheckIfNPCExists();
var_dump($data);
$result = $status->uniqueTest($data->npc_name);
if($result == '0'){
$npc_class = new InsertNPC();
$npc_result = $npc_class->createNew($data->npc_name,$data->npc_startdialog);
echo $npc_result;
}
$result is giving me an error about getting non-object property of 'npc_name'.
var_dump of $data shows in Chrome Preview:
object(stdClass)[1]
public 'npc_name'
but in Response slightly more (xdebug log):
<pre class='xdebug-var-dump' dir='ltr'>
<small>C:\xampp\htdocs\test\Quests\endpoints\insert.npc.php:12:</small>
<b>object</b>(<i>stdClass</i>)[<i>1</i>]
<i>public</i> 'npc_name' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'dupa'</font> <i>(length=4)</i>
<i>public</i> 'npc_startdialog' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>'dupa2'</font> <i>(length=5)</i>
</pre>
I would appreciate any help, any tips are welcome as well. The text limit is so unhandy.
Related
I am writing a wordpress block and I am getting these errors when displaying the block on the output page:
Warning: Undefined array key "title" in C:\xampp\htdocs\project\wp-content\plugins\opisyuslug\opisyuslug.php on line 44
Warning: Undefined array key "description" in C:\xampp\htdocs\project\wp-content\plugins\opisyuslug\opisyuslug.php on line 45
Warning: Undefined array key "image" in C:\xampp\htdocs\project\wp-content\plugins\opisyuslug\opisyuslug.php on line 46
How can I fix this?
PHP code:
function create_block_opisyuslug_block_init() {
register_block_type( __DIR__ . '/build' );
}
add_action( 'init', 'create_block_opisyuslug_block_init' );
function opisyuslug_block() {
wp_register_script(
'opisyuslug-block',
plugins_url( 'build/index.js', __FILE__ ),
array( 'wp-blocks', 'wp-element', 'wp-editor' )
);
register_block_type( 'opisyuslug/opisyuslug', array(
'editor_script' => 'opisyuslug-block',
'render_callback' => 'opisyuslug_block_render',
) );
}
add_action( 'init', 'opisyuslug_block' );
function opisyuslug_block_render($attributes) {
$title = $attributes['title'];
$description = $attributes['description'];
$image = $attributes['image'];
return '<div class="opisyuslug-block">
<h2>' . $title . '</h2>
<p>' . $description . '</p>
<img src="' . $image . '" />
</div>';
}
JS code:
"use strict";
var registerBlockType = wp.blocks.registerBlockType;
var _wp$blockEditor = wp.blockEditor,
RichText = _wp$blockEditor.RichText,
MediaUpload = _wp$blockEditor.MediaUpload;
registerBlockType('opisyuslug/opisyuslug', {
title: 'Opisy usług',
icon: 'block-default',
category: 'common',
attributes: {
title: {
type: 'string',
source: 'html',
selector: 'h3'
},
description: {
type: 'string',
source: 'html',
selector: 'p'
},
image: {
type: 'string',
source: 'attribute',
selector: 'img',
attribute: 'src'
}
},
edit: function edit(props) {
var _props$attributes = props.attributes,
title = _props$attributes.title,
description = _props$attributes.description,
image = _props$attributes.image,
setAttributes = props.setAttributes;
var onChangeTitle = function onChangeTitle(newTitle) {
setAttributes({
title: newTitle
});
};
var onChangeDescription = function onChangeDescription(newDescription) {
setAttributes({
description: newDescription
});
};
var onChangeImage = function onChangeImage(newImage) {
setAttributes({
image: newImage
});
};
return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("label", {
htmlFor: "title"
}, "Tytu\u0142:"), /*#__PURE__*/React.createElement(RichText, {
id: "title",
tagName: "h3",
value: title,
onChange: onChangeTitle
}), /*#__PURE__*/React.createElement("label", {
htmlFor: "description"
}, "Opis:"), /*#__PURE__*/React.createElement(RichText, {
id: "description",
tagName: "p",
value: description,
onChange: onChangeDescription
}), /*#__PURE__*/React.createElement(MediaUpload, {
onSelect: onChangeImage,
type: "image",
value: image,
render: function render(_ref) {
var open = _ref.open;
return /*#__PURE__*/React.createElement("button", {
onClick: open
}, image ? /*#__PURE__*/React.createElement("img", {
src: image
}) : 'dodaj obraz');
}
}));
},
save: function save(props) {
var _props$attributes2 = props.attributes,
title = _props$attributes2.title,
description = _props$attributes2.description,
image = _props$attributes2.image;
return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("h3", null, title), /*#__PURE__*/React.createElement("p", null, description), image && /*#__PURE__*/React.createElement("img", {
src: image
}));
}
});
Now I am trying to save some data user input into some forms and keep these in user's local device.
But, I have an error. ( Below pic)
I don't know why and how to solve this problem...
Followings are my code.
This is "state".
class PersonalInfo1 extends React.Component {
constructor(props) {
super(props);
this.state = {
userInput: [
{ fullname: '' },
{ middleName: '' },
{ reason: '' },
{ birthPlaceCity: '' },
{ birthPlaceCountry: '' },
{ Citizinchip: '' },
{ aboutMaridge: '' },
{ fromTermOfMaridge: '' },
{ ToTermOfMaridge: '' },
{ nameOfSpouse:'' },
{ birthdateOfSpouse: '' },
{ fromTermOfExMaridge: '' },
{ ToTermOfExMaridge: '' },
{ nameOfExSpouse: '' },
{ birthdateOfExSpouse: '' },
],
};
}
This is rest of code.
componentDidMount() {
AsyncStorage.getItem('userInput')
.then((userInput) => this.setState({ userInput }));
}
onChangeText(text, name) {
AsyncStorage.getItem('userInput')
.then((userInput) => {
if (userInput !== null) {
this.state.userInput[name] = text;
AsyncStorage.setItem('userInput', userInput);
}
});
}
const { userInput } = this.state;
return (
<ScrollView style={styles.container}>
<InfoHeader navigation={this.props.navigation}>
申請者情報1
</InfoHeader>
<Notes />
<QuestionTextSet
onChangeText={(text) => this.onChangeText(text, 'fullname')}
placeholder={'例:留学太郎'}
value={userInput.fullname}
editable
>
姓名(漢字表記)
</QuestionTextSet>
this.state.userInput is indexed array (0, 1, 2 ... ) with objects (e.g. { fullname: '' }) as a value. So, you can't access it in the following way:
this.state.userInput[name] = text;
Try to change this.state to the following one:
this.state = {
userInput:
{
fullname: '',
middleName: '',
reason: '',
birthPlaceCity: '',
birthPlaceCountry: '',
Citizinchip: '',
aboutMaridge: '',
fromTermOfMaridge: '',
ToTermOfMaridge: '',
nameOfSpouse: '',
birthdateOfSpouse: '',
fromTermOfExMaridge: '',
ToTermOfExMaridge: '',
nameOfExSpouse: '',
birthdateOfExSpouse: ''
}
};
... if it's acceptable in your case.
I'm creating a Reddit clone and I'm setting up the backend first, but having trouble creating relational data.
When I use this query:
query {
subreddit(id: 1) {
name
posts {
title
}
}
}
I expect:
{
"data": {
"subreddit": {
"name": "javascript"
"posts": [
{
"title": "JS Post"
}
]
}
}
}
What I get:
{
"data": null,
"errors": [
{
"message": "Cannot return null for non-nullable field Subreddit.posts.",
"locations": [
{
"line": 4,
"column": 5
}
],
"path": [
"subreddit",
"posts"
]
}
]
}
Here's the schema:
type Query {
subreddits: [Subreddit!]!
subreddit(id: ID!): Subreddit!
posts: [Post!]!
post(id: ID!): Post!
}
type Mutation {
createSubreddit(
name: String!
description: String!
contentType: String!
ageRestriction: Boolean!
): Subreddit!
}
type Subreddit {
id: ID!
name: String!
description: String!
contentType: String!
ageRestriction: Boolean!
posts: [Post!]!
}
type Post {
id: ID!
title: String!
body: String!
subredditId: ID!
# userId: ID!
}
Here is server/index.js:
const { GraphQLServer } = require('graphql-yoga');
let dummySubreddits = [
{
name: 'javascript',
description: 'all things javascript',
contentType: 'any',
ageRestriction: false,
id: 1
},
{
name: 'react',
description: 'all things react',
contentType: 'any',
ageRestriction: false,
id: 2
},
{
name: 'primsa',
description: 'all things prisma',
contentType: 'any',
ageRestriction: false,
id: 3
}
];
let idCountSubreddit = dummySubreddits.length;
let dummyPosts = [
{ title: 'JS Post', body: 'Body of post one', id: 1, subredditId: 1 },
{ title: 'React Post', body: 'Body of post two', id: 2, subredditId: 2 },
{
title: 'Prisma Post',
body: 'Body of post three',
id: 3,
subredditId: 3
}
];
let idCountPost = dummyPosts.length;
const resolvers = {
Query: {
subreddits: () => dummySubreddits,
subreddit: (parent, args) => {
return dummySubreddits.find(obj => obj.id == args.id);
},
posts: () => (parent, args) => {
return dummyPosts.find(obj => obj.subredditId == parent.id);
},
post: (parent, args) => {
return dummyPosts.find(obj => obj.id == args.id);
}
},
Mutation: {
createSubreddit: (parent, args) => {
let subreddit = {
id: idCountSubreddit++,
name: args.name,
description: args.description,
contentType: args.contentType,
ageRestriction: args.ageRestriction
};
return subreddit;
}
}
};
const server = new GraphQLServer({ typeDefs: './schema.graphql', resolvers });
server.start(() => console.log('Server is running on localhost:4000'));
I'm using the GraphQL desktop app for querying and I do not have grapql-yoga config file.
Where am I going wrong? I'd like to be pointed in the right direction so I can figure it out myself. This is my first time working with GraphQL alone, after doing some tutorials on YouTube, however they used graphql-express and I'm using graphql-yoga.
Move the resolver you have written for Query's posts into Subreddit to resolve the posts field there. If your resolver does not comply to the default resolver implementation:
(parent) => parent[fieldName]
Like in your case
(parent) => parent.posts
You have to specify it yourself. If your field posts on Query should display all the posts you might want to go for the following implementations:
const resolvers = {
Query: {
subreddits: () => dummySubreddits,
subreddit: (parent, args) => {
return dummySubreddits.find(obj => obj.id == args.id);
},
posts: () => dummyPosts,
post: (parent, args) => {
return dummyPosts.find(obj => obj.id == args.id);
}
},
Subreddit: {
posts: () => (parent, args) =>
dummyPosts.filter(obj => obj.subredditId == parent.id),
},
Mutation: {
createSubreddit: (parent, args) => {
let subreddit = {
id: idCountSubreddit++,
name: args.name,
description: args.description,
contentType: args.contentType,
ageRestriction: args.ageRestriction
};
return subreddit;
}
}
};
I had to add a resolver for subreddit to deal with posts.
const resolvers = {
Query: {
subreddits: () => dummySubreddits,
subreddit: (parent, args) => {
return dummySubreddits.find(obj => obj.id == args.id);
},
posts: (parent, args) => {
return dummyPosts;
},
post: (parent, args) => {
return dummyPosts.find(obj => obj.id == args.id);
}
},
Mutation: {
createSubreddit: (parent, args) => {
let subreddit = {
id: idCountSubreddit++,
name: args.name,
description: args.description,
contentType: args.contentType,
ageRestriction: args.ageRestriction
};
return subreddit;
}
},
// This resolver was needed
Subreddit: {
posts: subreddit =>
dummyPosts.filter(obj => obj.subredditId == subreddit.id)
}
};
If I create a new movie object, the associated username from owner (App.User) isn't shown. It shows only after I reload the page. Any idea how I can achieve to show immediately the associated username after I have created a new movie?
Code so far:
App.Movie = Ember.Model.extend({
objectId: Ember.attr(),
title: Ember.attr(),
year: Ember.attr(),
owner: Ember.belongsTo('App.User', {
key: 'owner',
serializer: UserType
})
});
App.User = Ember.Model.extend({
objectId: Ember.attr(),
username: Ember.attr(),
});
App.Movie.adapter = Ember.Adapter.create({
createRecord: function(record) {
return Ember.$.ajax({
headers: {
'X-Parse-Application-Id': '',
'X-Parse-REST-API-Key': ''
},
type: 'POST',
url: 'https://api.parse.com/1/classes/Movie',
contentType: 'application/json',
data: JSON.stringify(record)
}).then(function(data) {
record.load(data.objectId, record.get('_data'));
record.didCreateRecord();
});
}
});
{{#each movie in this}}
<tr>
<td>{{movie.year}}</td>
<td>{{movie.title}}</td>
<td>{{movie.owner.username}}</td>
</tr>
{{/each}}
App.MoviesIndexController = Ember.ArrayController.extend({
rawDescription: '',
year: '',
title: '',
errors: null,
actions: {
createMovie: function () {
var rawDescription = this.get('rawDescription');
if (!rawDescription.match(/([^$]+)(\d{4})/)) {
this.set('errors', {
rawDescription: 'Oh snap! Please include the movie\'s title and year.'
});
} else if (!this.isUnique({
rawDescription: rawDescription
})) {
this.set('errors', {
rawDescription: 'Oh snap! The movie already exists.'
});
} else {
var rv = this.parseRawDescription(this.get('rawDescription')),
title = rv[1],
year = rv[2],
newMovie = App.Movie.create({
owner: App.Session.authUser,
ratings: [{ objectId: App.Session.objectId, value: 0 }]
title: title,
watched: false,
year: year,
});
newMovie.save();
this.setProperties({ rawDescription: '', errors: null });
}
}
}
});
I'm showing it as working, are you sure App.Session.authUser is populated? if you try console.log(newMovie.get('owner.username')) after you create it does it show anything?
http://emberjs.jsbin.com/AYidAdi/1/edit
I have this grid
$("#email-grid").kendoGrid({
dataSource: {
transport: {
read: {
url: "operations/get_emails_sales_reps.php?salesRepsId=" + salesRepsId,
type: "GET"
},
update: {
url: "operations/edit_email.php?salesRepsId=" + salesRepsId,
type: "POST",
complete: function (e) {
$("#email-grid").data("kendoGrid").dataSource.read();
}
},
destroy: {
url: "operations/delete_email.php",
type: "POST",
complete: function (e) {
$("#email-grid").data("kendoGrid").dataSource.read();
}
},
create: {
url: "operations/add_email.php?salesRepsId=" + salesRepsId,
type: "POST",
complete: function (e) {
$("#email-grid").data("kendoGrid").dataSource.read();
}
},
},
schema: {
data: "data",
total: "data.length", //total amount of records
model: {
id: "SalesRepId",
fields: {
EmailType: {
defaultValue: {
EmailTypeId: 2,
EmailTypeName: "Home"
}
},
EmailText: {
type: "string"
},
IsMainEmail: {
type: "boolean"
}
}
}
},
pageSize: 5,
},
height: 250,
filterable: true,
sortable: true,
pageable: true,
reorderable: false,
groupable: false,
batch: true,
navigatable: true,
toolbar: ["create", "save", "cancel"],
editable: true,
columns: [{
field: "EmailType",
title: "Type",
editor: EmailTypeDropDownEditor,
template: "#=EmailType.EmailTypeName#"
}, {
field: "EmailText",
title: "Email",
}, {
field: "IsMainEmail",
title: "Main?",
width: 65,
template: function (e) {
if (e.IsMainEmail == true) {
return '<img align="center" src ="images/check-icon.png" />';
} else {
return '';
}
}
// hidden: true
}, {
command: "destroy",
title: " ",
width: 90
},
]
});
the code in the server side (get_emails_sales_reps.php)
<?php
require_once ("../lib/salesrep.php");
require_once ("../lib/helper.php");
// add the header line to specify that the content type is JSON
header("Content-type: application/json");
$options = array();
$result = SalesRep::getRepEmails($_GET["salesRepsId"]);
if (isset($result) && $result != null) {
$result = _object_to_array($result);
if (isset($result[0]) && is_array($result)) {
for ($i = 0; $i < count($result); $i++) {
$result[$i]["EmailType"] = array("EmailTypeName" => $result[$i]["EmailType"], "EmailTypeId" => $result[$i]["EmailTypeId"]);
}
} else {
$result["EmailType"] = array("EmailTypeName" => $result["EmailType"], "EmailTypeId" => $result["EmailTypeId"]);
}
if (isset($result) || $result != null) {
echo "{\"data\":" . json_encode($result) . "}";
} else {
echo "{\"data\": {} }";
}
}
?>
when the grid has one record or more, I can add new record without any errors, but when there are no records the grid and try to add a new record. I get this error
Uncaught TypeError: Cannot read property 'length' of undefined
please, how can I fix this ??
I've solved this issue by editing the php file. when result is null ( empty) I have to return an empty json array like this
else {
// the result is null
echo "{\"data\": [] }";
}