How to create relations between tables with knex on postgresql database [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 21 days ago.
Improve this question
Can you show me how can i realiton between 2 table with knex on postgresql that tables are 'user' , 'project' , 'post'. I want to make a relation like in project table i have 'user_id' column so it should be connect with 'user' table with id. also post too.My migration file like this.
/**
* #param { import("knex").Knex } knex
* #returns { Promise<void> }
*/
exports.up = function (knex) {
return knex.schema.createTable('user', (table) => {
table.increments().notNullable();
table.string('created_at').notNullable();
table.string('updated_at');
table.string('first_name').notNullable();
table.string('last_name').notNullable();
table.integer('age').notNullable();
table.string('email', 100);
table.text('user_image').notNullable();
table.jsonb('social_links'); //tek bir obje olcak
table.text('introduction');
table.text('description');
table.jsonb('medias'); //şüpheliyim
table.specificType('marked_projects', 'int[]');
table.specificType('marked_blogs', 'int[]');
table.specificType('experiences', 'jsonb[]');
table.specificType('education', 'jsonb[]'); //objeler arrayi olcak
table.specificType('skills', 'jsonb[]');
table.string('sign_mail');
table.string('password');
})
.createTable('project', (table) => {
table.increments().notNullable();
table.integer('user_id').notNullable();
table.string('project_name').notNullable();
table.string('project_type');
table.string('project_title').notNullable();
table.string('project_intro').notNullable();
table.string('intro_image').notNullable();
table.specificType('members', 'text[]');
table.jsonb('medias'); //kullanmıycağız şimdilik ama koyuyorum değişeiblir diye
table.specificType('paragraphs', 'jsonb[]');
table.specificType('links', 'text[]');
table.foreign('user_id').references('user.id')
.onUpdate('CASCADE')
.onDelete('CASCADE');
})
.createTable('post', (table) => {
table.increments().notNullable();
table.integer('user_id').notNullable();
table.string('post_name').notNullable();
table.string('post_type');
table.string('post_title').notNullable();
table.string('post_intro').notNullable();
table.string('intro_image').notNullable();
table.jsonb('medias'); //kullanmıycağız şimdilik ama koyuyorum değişeiblir diye
table.specificType('paragraphs', 'jsonb[]');
table.specificType('links', 'text[]');
table.foreign('user_id').references('user.id')
.onUpdate('CASCADE')
.onDelete('CASCADE');
})
};
/**
* #param { import("knex").Knex } knex
* #returns { Promise<void> }
*/
exports.down = function (knex) {
return knex.schema.dropTableIfExists('post')
.dropTableIfExists('project')
.dropTableIfExists('user');
};
Also i want to this connection:
Tables:| user | project | post |
so in my project table i have this column: 'user_id' , if my user_id: 2 i need to reach user that have id 2. This database should be relational database.
in post table i have 'user_id' column and its same too.
i want to reach which person did create a post and project.
if my migration is true why i cannot run my seeds.
my seed file like this:
/**
* #param { import("knex").Knex } knex
* #returns { Promise<void> }
*/
exports.seed = async function (knex) {
// Deletes ALL existing entries
await knex('user').del()
await knex('user').insert([
{
id: 1,
created_at: "02/04/2021",
updated_at: "02/04/2022",
first_name: "Betül",
last_name: "Özkan",
age: 23,
email: "omerdmrsy#gmail.com",
user_image: "https://t3.ftcdn.net/jpg/03/46/83/96/360_F_346839683_6nAPzbhpSkIpb8pmAwufkC7c5eD7wYws.jpg",
social_links: {
linkedn: "https://www.linkedin.com/in/%C3%B6mer-faruk-demirsoy-290642196/",
behance: "https://www.behance.net/betul-0zkan",
medium: "https://medium.com/#betul-0zkan",
instagram: "",
github: "https://github.com/OFD16",
},
introduction: "I am a 20-year-old, self-taught freelance UI/UX designer based in Turkey. My passion is to using design to inspire and impact others, so I make it a point to constantly improve my skills and write my learnings in both English and Turkish.",
description: "Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. ",
medias: {
videos: ["https://www.youtube.com/watch?v=lSIWNfNzJ18", "https://www.youtube.com/watch?v=G1GgjXbc6VM"],
images: ["https://t3.ftcdn.net/jpg/03/46/83/96/360_F_346839683_6nAPzbhpSkIpb8pmAwufkC7c5eD7wYws.jpg"],
},
marked_projects: [2, 7],
marked_blogs: [],
experiences: [
{ started_time: "01/01/2023", finished_time: "01/03/2023", company_name: "Figma", job_name: "UI/UX designer", introduction: "I am a 20-year-old, self-taught freelance UI/UX designer based in Turkey. My passion is to using design to inspire and impact others, so I make it a point to constantly improve my skills and write my learnings in both English and Turkish.", image: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/95/Instagram_logo_2022.svg/1000px-Instagram_logo_2022.svg.png" },
{ started_time: "01/01/2023", finished_time: "", company_name: "google", job_name: "coder", introduction: "I am a 20-year-old, self-taught freelance UI/UX designer based in Turkey. My passion is to using design to inspire and impact others, so I make it a point to constantly improve my skills and write my learnings in both English and Turkish.", image: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/95/Instagram_logo_2022.svg/1000px-Instagram_logo_2022.svg.png" }
],
education: [
{ started_time: "01/01/2015", finished_time: "01/03/2020", school_name: "EAİHL", degree: "Lise", image: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/95/Instagram_logo_2022.svg/1000px-Instagram_logo_2022.svg.png" },
{ started_time: "01/01/2020", finished_time: "01/03/2026", school_name: "AGÜ", degree: "lisans", image: "https://upload.wikimedia.org/wikipedia/commons/thumb/9/95/Instagram_logo_2022.svg/1000px-Instagram_logo_2022.svg.png" },
],
skills: [
{ skill_name: "java", experience_time: "6 ay", description: "Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales.", image: "https://upload.wikimedia.org/wikipedia/en/thumb/3/30/Java_programming_language_logo.svg/1200px-Java_programming_language_logo.svg.png" },
{ skill_name: "c++", experience_time: "1 ay", description: "Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales.", image: "https://upload.wikimedia.org/wikipedia/commons/thumb/1/18/ISO_C%2B%2B_Logo.svg/1822px-ISO_C%2B%2B_Logo.svg.png" },
],
sign_mail: "omer#gmail.com",
password: "123456"
},
]);
await knex('project').del()
await knex('project').insert([
{
id: 1,
user_id: 0,
project_name: "proje adı",
project_type: "proje tipi",
project_title: "proje başlıpı",
intro_image: "https://t3.ftcdn.net/jpg/03/46/83/96/360_F_346839683_6nAPzbhpSkIpb8pmAwufkC7c5eD7wYws.jpg",
project_intro: "I am a 20-year-old, self-taught freelance UI/UX designer based in Turkey. My passion is to using design to inspire and impact others, so I make it a point to constantly improve my skills and write my learnings in both English and Turkish.",
paragraphs: [
{
first_video: "",
first_image: "",
left_image: "",
paragpaph: "Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. ",
right_image: "",
last_image: "",
last_video: "",
},
{
first_video: "",
first_image: "",
left_image: "",
paragpaph: "Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. ",
right_image: "",
last_image: "",
last_video: "",
}
],
medias: {
videos: ["https://www.youtube.com/watch?v=lSIWNfNzJ18", "https://www.youtube.com/watch?v=G1GgjXbc6VM"],
images: ["https://t3.ftcdn.net/jpg/03/46/83/96/360_F_346839683_6nAPzbhpSkIpb8pmAwufkC7c5eD7wYws.jpg"],
},
members: ["ali", "ayşe"],
links: ["https://www.twitch.tv/", "https://www.twitch.tv/elraenn"]
},
{
id: 1,
project_name: "proje adı 1",
project_type: "proje tipi 1",
project_title: "proje başlıpı 1",
intro_image: "https://t3.ftcdn.net/jpg/03/46/83/96/360_F_346839683_6nAPzbhpSkIpb8pmAwufkC7c5eD7wYws.jpg",
project_intro: "1 I am a 20-year-old, self-taught freelance UI/UX designer based in Turkey. My passion is to using design to inspire and impact others, so I make it a point to constantly improve my skills and write my learnings in both English and Turkish.",
paragraphs: [
{
first_video: "",
first_image: "",
left_image: "",
paragpaph: "1 Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. ",
right_image: "",
last_image: "",
last_video: "",
},
{
first_video: "",
first_image: "",
left_image: "",
paragpaph: "1 Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. ",
right_image: "",
last_image: "",
last_video: "",
}
],
medias: {
videos: ["https://www.youtube.com/watch?v=lSIWNfNzJ18", "https://www.youtube.com/watch?v=G1GgjXbc6VM"],
images: ["https://t3.ftcdn.net/jpg/03/46/83/96/360_F_346839683_6nAPzbhpSkIpb8pmAwufkC7c5eD7wYws.jpg"],
},
members: ["1ali", "a1yşe"],
links: ["https://www.twitch.tv/", "https://www.twitch.tv/elraenn"]
}
]);
await knex('post').del()
await knex('post').insert([
{
id: 1,
user_id: 1,
post_name: "post adı 1",
post_type: "post tipi 1",
post_title: "post başlıpı 1",
intro_image: "https://t3.ftcdn.net/jpg/03/46/83/96/360_F_346839683_6nAPzbhpSkIpb8pmAwufkC7c5eD7wYws.jpg",
post_intro: "1 I am a 20-year-old, self-taught freelance UI/UX designer based in Turkey. My passion is to using design to inspire and impact others, so I make it a point to constantly improve my skills and write my learnings in both English and Turkish.",
paragraphs: [
{
first_video: "",
first_image: "",
left_image: "",
paragpaph: "1 Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. ",
right_image: "",
last_image: "",
last_video: "",
},
{
first_video: "",
first_image: "",
left_image: "",
paragpaph: "1 Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. Lorem ipsum dolor sit amet consectetur. In volutpat sed quis tortor magna libero mi. At aliquam nec consectetur sem eget nunc aliquam. In adipiscing sit tristique nunc sodales. Id nisi libero massa mi senectus quis. Erat varius tortor lobortis et nunc laoreet cras. ",
right_image: "",
last_image: "",
last_video: "",
}
],
medias: {
videos: ["https://www.youtube.com/watch?v=lSIWNfNzJ18", "https://www.youtube.com/watch?v=G1GgjXbc6VM"],
images: ["https://t3.ftcdn.net/jpg/03/46/83/96/360_F_346839683_6nAPzbhpSkIpb8pmAwufkC7c5eD7wYws.jpg"],
},
links: ["https://www.twitch.tv/", "https://www.twitch.tv/elraenn"]
}
]);
};
and this is the error:
Error while executing "C:\Users\CABBAR\Desktop\projelerim\portfolio-backend\src\data\seeds\user.js" seed: insert into "project" ("id", "intro_image", "links", "medias", "members", "paragraphs", "project_intro", "project_name", "project_title", "project_type", "user_id") values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11), ($12,
$13, $14, $15, $16, $17, $18, $19, $20, $21, DEFAULT) - column "user_id" of relation "project" does not exist
Error: Error while executing "C:\Users\CABBAR\Desktop\projelerim\portfolio-backend\src\data\seeds\user.js" seed: insert into "project" ("id", "intro_image", "links",
"medias", "members", "paragraphs", "project_intro", "project_name", "project_title", "project_type", "user_id") values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11), ($12, $13, $14, $15, $16, $17, $18, $19, $20, $21, DEFAULT) - column "user_id" of relation "project" does not exist
at Seeder._waterfallBatch (C:\Users\CABBAR\Desktop\projelerim\portfolio-backend\node_modules\knex\lib\migrations\seed\Seeder.js:118:23)
error: insert into "project" ("id", "intro_image", "links", "medias", "members", "paragraphs", "project_intro", "project_name", "project_title", "project_type", "user_id") values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11), ($12, $13, $14, $15, $16, $17, $18, $19, $20, $21, DEFAULT) - column "user_id" of relation "project" does not exist
at Parser.parseErrorMessage (C:\Users\CABBAR\Desktop\projelerim\portfolio-backend\node_modules\pg-protocol\dist\parser.js:287:98)
at Parser.handlePacket (C:\Users\CABBAR\Desktop\projelerim\portfolio-backend\node_modules\pg-protocol\dist\parser.js:126:29)
at Parser.parse (C:\Users\CABBAR\Desktop\projelerim\portfolio-backend\node_modules\pg-protocol\dist\parser.js:39:38)
at Socket.<anonymous> (C:\Users\CABBAR\Desktop\projelerim\portfolio-backend\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (node:events:513:28)
at addChunk (node:internal/streams/readable:324:12)
at readableAddChunk (node:internal/streams/readable:297:9)
at Readable.push (node:internal/streams/readable:234:10)
at TCP.onStreamRead (node:internal/stream_base_commons:190:23)
but i have this user in my database:
i have user that have id : 1

Welcome to the StackOverflow community.
Update: The author updated the post later with new information. Not sure how much this answer is relevant for the current scenario, but I will keep it posted because other new learners may find it helpful.
However, your issue seems related to foreign key constraints not being created in the database.
I am also a student; here is a small one-to-many relationship using knex.js.
knex.schema.createTable('user', function(table) {
table.increments('id').primary();
table.string('name');
})
.createTable('project', function(table) {
table.increments('id').primary();
table.string('name');
table.integer('user_id').unsigned().references('user.id');
})
.createTable('post', function(table) {
table.increments('id').primary();
table.string('title');
table.integer('project_id').unsigned().references('project.id');
});
create a user table with an id and name column
create a project table with 'id,' 'name,' and 'user_id' columns
create a post table with 'id,' 'title,' and 'project_id' columns
The 'user_id' column in the project table and the 'project_id' column in the post table are foreign keys referencing the 'id' column in the respective tables.
Hope you find it helpful, don't forget to share areas of improvement in my comment, thanks

Related

vue slots and HTML from objects

I have some data in my vue component that looks like this,
items: [
{
slug: 'this-is-title-1',
title: 'This is title 1',
content:
'<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut et diam quis sem mollis viverra quis sed arcu. Nulla id nulla mollis tortor eleifend aliquam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Suspendisse quam ipsum, egestas sed lacus a, egestas pretium lorem. Nam non metus quis nulla porta porttitor. Etiam fringilla lorem sed sem dapibus cursus. Maecenas commodo lorem lorem, eu mollis urna aliquam vitae. Vestibulum sit amet ligula a risus dignissim elementum. Nunc volutpat turpis diam, eu lacinia sapien commodo in. Nulla euismod lorem non sapien pharetra consequat. Sed cursus vehicula molestie. Ut a tristique est.</p>'
},
{
slug: 'this-is-title-2',
title: 'This is title 2',
content:
'<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut et diam quis sem mollis viverra quis sed arcu. Nulla id nulla mollis tortor eleifend aliquam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Suspendisse quam ipsum, egestas sed lacus a, egestas pretium lorem. Nam non metus quis nulla porta porttitor. Etiam fringilla lorem sed sem dapibus cursus. Maecenas commodo lorem lorem, eu mollis urna aliquam vitae. Vestibulum sit amet ligula a risus dignissim elementum. Nunc volutpat turpis diam, eu lacinia sapien commodo in. Nulla euismod lorem non sapien pharetra consequat. Sed cursus vehicula molestie. Ut a tristique est.</p>'
},
],
I am looping over the data in inserting the content attribute into a slot, like so,
<template #content>
{{ item.content }}
</template>
This is getting rendered out as just a string not has HTML is there something I can do to make my slot parse HTML? I assumed I wouldn't no have to use v-html which I would still prefer not to do due to the content coming from a CMS and xss risks.

Mongodb: words disappeare from String filed

I'm facing a strange problem with mongodb database. In the following schema; i store in the field instructions a long text, and stragely sometimes i find that few words have disappeared from it.
const CourseSchema = new mongoose.Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
instructions: {
type: String,
default: '',
trim: true
}
});
I'm sorry i dont have more details about the issue, so i need some suggestion or ideas that could help.
Thanks
UPDATE:
Here is an exemple:
The original value :
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed et nulla pellentesque, consectetur velit pellentesque, consectetur dui. Nulla purus ante, eleifend vitae ornare ut, molestie quis metus. Nulla a augue ut orci fermentum blandit vel et elit. Pellentesque fermentum arcu erat. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec vitae posuere libero. Etiam non ex non risus ornare laoreet ac in tortor. Quisque malesuada tortor vulputate neque bibendum, bibendum vestibulum lacus cursus. Sed ac condimentum purus. Pellentesque nec tincidunt odio. Mauris ac tellus interdum, luctus augue et, cursus ex. Duis vulputate arcu at enim tincidunt, ut hendrerit mauris dapibus. Vivamus ullamcorper eu nisl et fringilla. Sed vel ornare sem. Proin porta erat sit amet nulla rhoncus tincidunt.
after few days (moment or whatever), i found:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed et nulla pellentesque, consectetur velit pellentesque, consectetur dui. Nulla purus ante, eleifend vitae ornare ut, molestie quis metus. Nulla a augue ut orci fermentum blandit vel et elit. Pellentesque fermentum arcu erat. Interdum et malesuada fames ac ante ipsum primis in faucibus. Donec vitae posuere libero. Etiam non ex non risus ornare laoreet ac in tortor. Quisque malesuada tortor vulputate neque bibendum, bibendum vestibulum lacus cursus. Sed ac condimentum purus. Pellentesque nec tincidunt odio. Mauris ac tellus interdum, luctus augue et, cursus ex. Duis vulputate arcu at enim tincidunt, ut hendrerit mauris dapibus. Vivamus ullamcorper eu nisl et fringilla. Sed vel ornare sem. Proin porta erat sit amet

how to dynamically change data based on JSON file using jQuery

<div id="rightside">
<h1>Name Of Person</h1>
<p>1900-1950
<p>Learn More
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur porta dictum turpis, eu mollis justo gravida ac. Proin non eros blandit, rutrum est a, cursus quam. Nam ultricies, velit ac suscipit vehicula, turpis eros sollicitudin lacus, at
convallis mauris magna non justo. Etiam et suscipit elit. Morbi eu ornare nulla, sit amet ornare est. Sed vehicula ipsum a mattis dapibus. Etiam volutpat vel enim at auctor.</p>
<p>Aenean pharetra convallis pellentesque. Vestibulum et metus lectus. Nunc consectetur, ipsum in viverra eleifend, erat erat ultricies felis, at ultricies mi massa eu ligula. Suspendisse in justo dapibus metus sollicitudin ultrices id sed nisl.</p>
<button>Pause</button>
</div>
my div looks like this. I want to replace it with data that I am getting from a JSON file. However I only want to show 1 entry at a time and make it animate between entries (does not need to be fancy).
My question is how can I get jQuery to change between my JSON data?
My JSON data looks like
[
{
"name": "Elizabeth Cady Stanton",
"image": "media/images/elizabeth.jpg",
"year": "1815 – 1902",
"wikilink": "https://en.wikipedia.org/wiki/Elizabeth_Cady_Stanton",
"article": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur porta dictum turpis, eu mollis justo gravida ac. Proin non eros blandit, rutrum est a, cursus quam. Nam ultricies, velit ac suscipit vehicula, turpis eros sollicitudin lacus, at convallis mauris magna non justo. Etiam et suscipit elit. Morbi eu ornare nulla, sit amet ornare est. Sed vehicula ipsum a mattis dapibus. Etiam volutpat vel enim at auctor. Aenean pharetra convallis pellentesque. Vestibulum et metus lectus. Nunc consectetur, ipsum in viverra eleifend, erat erat ultricies felis, at ultricies mi massa eu ligula. Suspendisse in justo dapibus metus sollicitudin ultrices id sed nil."
},
I would appreciate any help or links to examples.
Thanks
Added data-index to track data index that we are showing
<div id="rightside" data-index='-1'>..</div>
It will change your data after every 5 seconds in rotating manner.
setTimeout(function(){
var yourJsonData = [{"name":"Elizabeth Cady Stanton","image":""media/images/elizabeth.jpg"},{"name":"Elizabeth Cady Stanton","image":""media/images/elizabeth.jpg"}];
var currentIndex = $("#rightside").attr('data-index');
var totalLengthOfData = yourJsonData.length;
var indexToShow = currentIndex+1;
if(indexToShow > totalLengthOfData){
indexToShow=0;
}
$("#rightside").attr('data-index',indexToShow);
var dataToAppend = yourJsonData[indexToShow];
$("#rightside").children().remove();
$("#rightside").append("<h1>"+yourJsonData['name']+"</h1>").
append("<p>"+yourJsonData['year']+"</p><p><a href='"+yourJsonData['linktowiki']+"'>learn more</a></p>");
},5000);
haven't tested the code yet
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function () {
var yourJsonData = '[{"name": "Elizabeth Cady Stanton","image": "media/images/elizabeth.jpg","year": "1815 – 1902","wikilink": "https://en.wikipedia.org/wiki/Elizabeth_Cady_Stanton", "article": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur porta dictum turpis, eu mollis justo gravida ac. Proin non eros blandit, rutrum est a, cursus quam. Nam ultricies, velit ac suscipit vehicula, turpis eros sollicitudin lacus, at convallis mauris magna non justo. Etiam et suscipit elit. Morbi eu ornare nulla, sit amet ornare est. Sed vehicula ipsum a mattis dapibus. Etiam volutpat vel enim at auctor. Aenean pharetra convallis pellentesque. Vestibulum et metus lectus. Nunc consectetur, ipsum in viverra eleifend, erat erat ultricies felis, at ultricies mi massa eu ligula. Suspendisse in justo dapibus metus sollicitudin ultrices id sed nil."}]'
var obj = JSON.parse(yourJsonData);
$('#rightside').find('h1:first').text(obj[0].name);
$('#rightside').find('p:first').text(obj[0].year);
$('#rightside').find('a:first').attr('href', obj[0].wikilink)
$('#rightside').find('p:eq(3)').text(obj[0].article)
});
</script>
<body>
<div id="rightside">
<h1>Name Of Person</h1>
<p>1900-1950
<p>Learn More
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur porta dictum turpis, eu mollis justo gravida ac. Proin non eros blandit, rutrum est a, cursus quam. Nam ultricies, velit ac suscipit vehicula, turpis eros sollicitudin lacus, at
convallis mauris magna non justo. Etiam et suscipit elit. Morbi eu ornare nulla, sit amet ornare est. Sed vehicula ipsum a mattis dapibus. Etiam volutpat vel enim at auctor.</p>
<p>Aenean pharetra convallis pellentesque. Vestibulum et metus lectus. Nunc consectetur, ipsum in viverra eleifend, erat erat ultricies felis, at ultricies mi massa eu ligula. Suspendisse in justo dapibus metus sollicitudin ultrices id sed nisl.</p>
<button>Pause</button>
</div>
</body>
</html>
Your problem can be solved by this:
HTML:
<div id="rightside">
<h1 id="nameOfPerson"></h1>
<p id="year">
</p>
<a id="wikiLink">Learn More</a>
<p id="article"></p>
<p></p>
<button id="fill">Start</button>
</div>
JQuery :
var dataObject = [{
"name": "Elizabeth Cady Stanton",
"image": "media/images/elizabeth.jpg",
"year": "1815 – 1902",
"wikilink": "https://en.wikipedia.org/wiki/Elizabeth_Cady_Stanton",
"article": "Whole Article"
}];
$("#fill").click(function() {
setData(dataObject);
});
var setData = function(data) {
$.each(data, function(index, mainData) {
$("#nameOfPerson").text(mainData.name);
$("#year").text(mainData.year);
$("#wikiLink").attr("href",mainData.wikilink);
$("#article").text(mainData.article)
});
};
By this code your data will be rendered dynamically.
For Demo you can check my fiddle :
Fiddle Link Here

Remove two "limit" strings and its content

So, I have this text:
Lorem ipsum dolor sit amet, wrong text: consectetur adipiscing
elit. Donec quis libero erat. Integer auctor congue odio, end of
wrong text eget condimentum dui. Nam consectetur ut odio vitae
egestas. Ut tincidunt mi lectus, a lobortis ante malesuada ac. Etiam
tristique nunc finibus, wrong text: tincidunt lectus ac, sagittis urna.
Vestibulum end of wrong text
quis maximus libero, eu viverra urna. Morbi a tempor ex.
I would like to remove the phrases in bold and its content with JS and Regex if possible.
EDIT: Maybe I haven't made myself clear, I am asking to remove all the text between "wrong text: " and "end of wrong text" and both of the other words so the text would become like:
Lorem ipsum dolor sit amet, eget condimentum dui. Nam consectetur ut odio vitae
egestas. Ut tincidunt mi lectus, a lobortis ante malesuada ac. Etiam
tristique nunc finibus,
quis maximus libero, eu viverra urna. Morbi a tempor ex.
Try this:
string.replace(/wrong text:.*?end of wrong text/g, '')

Open a multi open accordion tab and scroll to a hash location within that section (IE scrolling to hash anchor before evaluating query string?)

How can I create links that will expand a particular accordion section and then scroll to a particular DIV within that section?
I'm using the latest jQuery UI library as well as jquery.multi-accordion-1.5.3.js, and developing for IE8 or later
I've been able to successfully implement both multiAccordion and by parsing a query string I can manipulate which section to be expanded, and scroll to the first hash anchor.
Strangely, this seems to work only for the first link, for any other link it scrolls past the corresponding hash anchor, and overall it acts erratically.
I came across a few threads mentioning IE having issues recognizing hash anchors in a query string like this index.php?page=page1#section3 , ie...Why does Internet Explorer not support bookmarks with both a querystring and a hash/anchor? Firefox works properly but I have not come across one solution...
Has anyone have a solution for this? Any alternatives?
Here is my code (or if it's more legible for you - the fiddle with the same code http://jsfiddle.net/3QSmq/1/)
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>jQuery UI Multi Open Accordion</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=8"/>
<link type="text/css" rel="stylesheet" href="css/jquery-ui-1.8.9.custom/jquery-ui-1.8.9.custom.css" />
<script type="text/javascript" src="jquery-1.4.3.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.13.custom.min.js"></script>
<script type="text/javascript" src="jquery.multi-accordion-1.5.3.js"></script>
<style type="text/css">
/*demo page css*/
body{ font: 62.5% "Trebuchet MS", sans-serif; margin: 50px;}
</style>
</head>
<body>
SOMETHING<br />
SOMETHING1
<div id="multiAccordion">
<h3>tab 1</h3>
<div>Text here
</div>
<h3>tab 2</h3>
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu mauris nulla, at cursus nulla. Morbi venenatis, risus sit amet ultricies pharetra, lorem purus tempor risus, vel tincidunt lectus nisi sit amet neque. Aenean sit amet nibh orci, a gravida eros. Pellentesque dignissim, libero eu congue semper, mauris metus molestie nisi, vitae posuere felis leo ac lectus. Mauris a nisi eget sapien varius eleifend vel vel nibh. In placerat commodo blandit. Vivamus sagittis ante sed nisl sodales id luctus diam dapibus. Proin a felis tristique nulla rhoncus sollicitudin. Nullam sit amet neque augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce at nisi sapien.
<p id="something" style="color:red">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu mauris nulla, at cursus nulla. Morbi venenatis, risus sit amet ultricies pharetra, lorem purus tempor risus, vel tincidunt lectus nisi sit amet neque. Aenean sit amet nibh orci, a gravida eros. Pellentesque dignissim, libero eu congue semper, mauris metus molestie nisi, vitae posuere felis leo ac lectus. Mauris a nisi eget sapien varius eleifend vel vel nibh. In placerat commodo blandit. Vivamus sagittis ante sed nisl sodales id luctus diam dapibus. Proin a felis tristique nulla rhoncus sollicitudin. Nullam sit amet neque augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce at nisi sapien.
</p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu mauris nulla, at cursus nulla. Morbi venenatis, risus sit amet ultricies pharetra, lorem purus tempor risus, vel tincidunt lectus nisi sit amet neque. Aenean sit amet nibh orci, a gravida eros. Pellentesque dignissim, libero eu congue semper, mauris metus molestie nisi, vitae posuere felis leo ac lectus. Mauris a nisi eget sapien varius eleifend vel vel nibh. In placerat commodo blandit. Vivamus sagittis ante sed nisl sodales id luctus diam dapibus. Proin a felis tristique nulla rhoncus sollicitudin. Nullam sit amet neque augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce at nisi sapien.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu mauris nulla, at cursus nulla. Morbi venenatis, risus sit amet ultricies pharetra, lorem purus tempor risus, vel tincidunt lectus nisi sit amet neque. Aenean sit amet nibh orci, a gravida eros. Pellentesque dignissim, libero eu congue semper, mauris metus molestie nisi, vitae posuere felis leo ac lectus. Mauris a nisi eget sapien varius eleifend vel vel nibh. In placerat commodo blandit. Vivamus sagittis ante sed nisl sodales id luctus diam dapibus. Proin a felis tristique nulla rhoncus sollicitudin. Nullam sit amet neque augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce at nisi sapien.
</div>
<h3>tab 3</h3>
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu mauris nulla, at cursus nulla. Morbi venenatis, risus sit amet ultricies pharetra, lorem purus tempor risus, vel tincidunt lectus nisi sit amet neque. Aenean sit amet nibh orci, a gravida eros. Pellentesque dignissim, libero eu congue semper, mauris metus molestie nisi, vitae posuere felis leo ac lectus. Mauris a nisi eget sapien varius eleifend vel vel nibh. In placerat commodo blandit. Vivamus sagittis ante sed nisl sodales id luctus diam dapibus. Proin a felis tristique nulla rhoncus sollicitudin. Nullam sit amet neque augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce at nisi sapien.
<p id="something1" style="color:red">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu mauris nulla, at cursus nulla. Morbi venenatis, risus sit amet ultricies pharetra, lorem purus tempor risus, vel tincidunt lectus nisi sit amet neque. Aenean sit amet nibh orci, a gravida eros. Pellentesque dignissim, libero eu congue semper, mauris metus molestie nisi, vitae posuere felis leo ac lectus. Mauris a nisi eget sapien varius eleifend vel vel nibh. In placerat commodo blandit. Vivamus sagittis ante sed nisl sodales id luctus diam dapibus. Proin a felis tristique nulla rhoncus sollicitudin. Nullam sit amet neque augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce at nisi sapien.
</p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu mauris nulla, at cursus nulla. Morbi venenatis, risus sit amet ultricies pharetra, lorem purus tempor risus, vel tincidunt lectus nisi sit amet neque. Aenean sit amet nibh orci, a gravida eros. Pellentesque dignissim, libero eu congue semper, mauris metus molestie nisi, vitae posuere felis leo ac lectus. Mauris a nisi eget sapien varius eleifend vel vel nibh. In placerat commodo blandit. Vivamus sagittis ante sed nisl sodales id luctus diam dapibus. Proin a felis tristique nulla rhoncus sollicitudin. Nullam sit amet neque augue. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Fusce at nisi sapien.
</div>
<h3>tab 4</h3>
<div>Text Here
</div>
</div>
JavaScript
$(function(){
$('#multiAccordion').multiAccordion({
active: [1, 2],
click: function(event, ui) {
//console.log('clicked')
},
init: function(event, ui) {
//console.log('whoooooha')
},
tabShown: function(event, ui) {
//console.log('shown')
},
tabHidden: function(event, ui) {
//console.log('hidden')
}
});
$('#multiAccordion').multiAccordion("option", "active", [y]);
});
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var x = getQueryVariable("page");
switch (x){
case(x = "tab1"):
y = 0;
break;
case(x = "tab2"):
y = 1;
break;
case(x = "tab3"):
y = 2;
break;
case(x = "tab4"):
y = 3;
break;
case(x = false):
y = "";
break;
default:
y ="";
break;
}
Any suggestions?
P.S. Here is THE closest description of my issue elsewhere on the web but no answer...Another thread
Instead of including the tab with the page, just target the ID from the hash. So your links will look like this:
SOMETHING<br />
SOMETHING1
Then you can include this code to find the ID from the hash, find the correct tab and open it. Here is the complete code & demo:
$(function() {
var updateAccordion = function(hash) {
hash = hash || window.location.hash;
var content, tab;
// look for a hash
if (hash && $(hash).length) {
// find accordion content
content = $(hash).closest('.ui-accordion-content');
if (content.length) {
// find "tab#" from <a> inside of accordion header (h3)
tab = parseInt(content.prev('h3').find('a').attr('id').replace('tab',''), 10) - 1;
$('#multiAccordion').multiAccordion("option", "active", [tab]);
}
}
};
// intercept all clicked links and look for a hash
$('a').click(function(){
if (this.hash) {
updateAccordion(this.hash);
}
});
$('#multiAccordion').multiAccordion({
active: [1],
click: function(event, ui) {
//console.log('clicked')
},
init: function(event, ui) {
//console.log('whoooooha')
},
tabShown: function(event, ui) {
//console.log('shown')
},
tabHidden: function(event, ui) {
//console.log('hidden')
}
});
// open up accordion to correct tab after initialization
updateAccordion();
});​
Try using document.location.hash to access directly the hash parameters.
In your example :
index.html?page=tab2#something
document.location.search will be ?page=tab2
document.location.hash will be #something
You are trying to parse the wrong value, so I guess the JQuery plugin scroll to the bottom of the page when it's trying to open a tab that doesn't exists.

Categories

Resources