Click here to Skip to main content
15,041,788 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to create a program that allows users to create lists and save data inside lists. I have created two pages first page has the data and second page where you create a list. Let me tell you the problem, as if I create three lists and I would like to save the data in the second list by onclick, but the data is saved in all three lists.

What I have tried:

Here is the first page which has data.

page1.js
'items and domore are the data for now.'
const apiSchema = 'http://localhost:5000/api/Schema'
const TableBody = document.querySelector('#recieve-info');
let items = 'hey'
let domore = 'hi'
TableBody.addEventListener('click', async (e) => {
    let SaveButtonPressed = e.target.id == 'save-button'
    if (SaveButtonPressed) {
        let data = { items, domore }
        let options = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        };
        
        const response = await fetch(apiSchema, options);
        const json = await response.json();
        console.log(json);
    }
});

// GETTING list value FROM THE LIST PAGE 
const ItemConnectionUrl = 'http://localhost:5000/item/Schema';
let Output = '';

const renderDataItem = (datas) => {
    datas.forEach((Item) => {
        Output += `
        <tr class = "tr">
            <td name = "dynamicValue">${Item.data}</td> 
            <td name = "button"> <button class="Save-Button" id="save-button">Save</button> </td>
        </tr>`
    });
    TableBody.innerHTML = Output;
}

fetch(ItemConnectionUrl)
        .then(res => res.json())
        .then(data => renderDataItem(data));



Here is the model of page1
model1.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const api_list = new Schema({
    data: Array
});

module.exports = mongoose.model('api_list', api_list);


Here is the route of first page
route1.js
const express = require('express');
const router = express();
const bodyparser = require("body-parser")
const mongoose = require('mongoose');
const { json } = require('body-parser');
const apiSchema = require('../models/page1');

// GET REQUEST '/api/Schema'
    router.get('/', async (req,res) => {
        try{
            const apis = await apiSchema.find();
            if(!apis) throw Error('No list');
    
            res.status(200).json(apis);
        }catch(err){
            res.status(400).json({msg : err});
        }
    });
    
    
    //POST REQUEST '/api/Schema'
    router.post('/', async (req, res) => {
        let data =req.body
        const apilist = new apiSchema({data});
        console.log(apilist)
    
        try{
            const api = await apilist.save();
            if(!api) throw Error('Something went wrong while saving to list');
    
            res.status(200).json({api});
    
        } catch(err) {
            res.status(400).json({msg : err});

}
    });


Here is the screenshot of first page (list1, list2, list3) come from the lists page. I would like that if i click the second list(list2) button I want the data to be saved in the second list on the lists page.
Screenshot of first page

Here is the second page where you create a list (lists page)
page2.js (lists page)

const TableBody = document.querySelector('#tableBody');
const addItemForm = document.querySelector('.add-item-form')
const titleValue = document.querySelector('#title');
const addButton = document.querySelector('#add')
let Output = '';
const ItemConnectionUrl = 'http://localhost:5000/item/Schema'

const renderDataItem = (datas) => {
    datas.forEach((Item) => {
        Output += `<tr data-id=${Item._id}>
        <td scope="row">class="fas fa-arrow-right" id="open" data-modal-target="#modal"></button></td> 

        <td class="table-buttons"><button class="btn btn-sm btn-danger delete-btn" id="delete_btns">^__i class="fas fa-trash-alt icon icon-modify"></button></td>


      </tr>`
    });
    TableBody.innerHTML = Output
}

// Create - Read item 
// METHOD : GET
fetch(ItemConnectionUrl)
.then(res => res.json())
.then(data => renderDataItem(data));


// SELECTING TABLE 
TableBody.addEventListener('click', (e) => {
 e.preventDefault();
 let deleteButton = e.target.id == 'delete_btns'
 let editButton = e.target.id == 'edit_btn'

 let id = e.target.parentElement.parentElement.dataset.id;

//DELETE-- Remove existing value
// METHOD: Delete
if(deleteButton){
  fetch(`${ItemConnectionUrl}/${id}`, {
    method : 'DELETE',
  })
  .then(res => res.json())
  .then(() => location.reload())
}

//EDIT-- Remove existing value
// METHOD: Patch
if(editButton){
  const edit = e.target.parentElement.parentElement;
  let dataContent = edit.querySelector('.ele').textContent;

  titleValue.value = dataContent;
  addButton.addEventListener('click', (e) => {
    e.preventDefault()
    fetch(`${ItemConnectionUrl}/${id}`,{
      method : 'PATCH',
      headers : {
        'Content-Type' : 'application/json'
      },
      body : JSON.stringify({
        data : titleValue.value
      })
    })
    .then(res => res.json())
    .then(() => location.reload())
  });
};

});

// Create - Inset new item 
// METHOD : POST
addItemForm.addEventListener('submit', (e) => {
  e.preventDefault();
  fetch(ItemConnectionUrl, {
    method : 'POST',
    headers:{
      'Content-Type': 'application/json'
    },
    body : JSON.stringify({
      data : titleValue.value
    })
  })
  .then(res => res.json())
  .then(data => {
    const dataArr = [];
    dataArr.push(data)
    renderDataItem(dataArr)
  });

  // RESET INPUT VALUE TO EMPTY
  titleValue.value=''
});


//Here is where you get the data from page1

const apiSchema = 'http://localhost:5000/api/schema'
async function ParaG() {
  const response = await fetch(apiSchema);
  const data  = await response.json();
  console.log(data);

  for (let item of data) {
    let info = item.data[0]
    const para = document.querySelector('.Second-Para');
    para.innerHTML += `${info.items}, ${info.domore}`
  }

}


Here is the model of page 2
model2.js
const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    const item_list = new Schema({
        data : String
    });
    
    module.exports = mongoose.model('item_list', item_list);


Here is the route 2
route2.js
const express = require('express');
const router = express();
const bodyparser = require("body-parser");
const mongoose = require('mongoose');
const { request, response } = require('express');
const itemSchema = require('../models/page2');

// GET REQUEST '/item/Schema'
router.get('/', async (req, res) => {

        res.status(200).json(items);

    } catch (err) {
        res.status(400).json({ msg: err });
    }
});

// GET REQUEST '/item/Schema/:id' GET A SPECIFIC ID
router.get('/:id', async (req, res) => {
    try {
        const items = await itemSchema.findById(req.params.id);
        if (!items) throw Error('No list');

        res.status(200).json(items);

    } catch (err) {
        res.status(400).json({ msg: err });
    }
});


// POST REQUEST '/item/Schema'
router.post('/', async (req, res) => {
    const itemlist = new itemSchema(req.body);

    try {
        const item = await itemlist.save();
        if (!item) throw Error('Something went wrong while saving to list');

        res.status(200).json(item);

    } catch (err) {
        res.status(400).json({ msg: err });
    }
});

// DELETE REQUEST '/item/Schema/:id'
router.delete('/:id', async (req, res) => {
    try {
        const item = await itemSchema.findByIdAndDelete(req.params.id);

        if (!item) throw Error('no list found');
        res.status(200).json({ success: true })
    } catch (err) {
        res.status(400).json({ msg: err });
    }
});

// UPDATE REQUEST '/item/Schema/:id'
router.patch('/:id', async (req, res) => {
    try {
        const item = await itemSchema.findByIdAndUpdate(req.params.id, req.body);

        if (!item) throw Error('Something went wrong while updating the list');
        res.status(200).json({ success: true })
    } catch (err) {
        res.status(400).json({ msg: err });
    }
});

// GET REQUEST '/item/Schema TRANSFER TO THE BOOKS PAGE'
router.get('/', async (req, res) => {
    try {
        const items = await itemSchema.find();
        if (!items) throw Error('No list');

        res.json(items)

    } catch (err) {
        res.status(400).json({ msg: err });
    }
});

All lists are linked to a pop up modal where i want the data to be saved
Screenshot of lists page

screenshot of lists page where i want the data to be saved.
Where i want the data to be saved

Can anyone help me. Thanks
Posted
Updated 1-Mar-21 8:59am

1 solution

You have to first consider that security makes it impossible to for a web page on your client to access another webpage - UNLESS - the targeted page is a child page of the one that sending the data.

If that's the case, you can use the DOM to access content on the child page (make sure they have ID's !). I use this technique in a parallel logic to exchange data between a page and an <iframe> on that page. It's basically the same thing.


   
Comments
Deep Dipe 1-Mar-21 16:24pm
   
Can you please give me another example to understand better,Thanks
W Balboos, GHB 2-Mar-21 7:51am
   
https://www.w3schools.com/jsref/met_win_open.asp
On this page you'll see an example of opening a child wind, how to make sure it's in a different tab, and, at the bottom, the return value
"Return Value: A reference to the newly created window, or null if the call failed"

You can use that reference to access things within the window you created from the window that created it. NEXT, look at the examples on the page - they show you how one page can put data on another.

Note: if you find your question answered, here on the Q&A, then please remember to mark it answered with the answer you have used (to help others in need and save the time of helpers who will know it's done).
Deep Dipe 2-Mar-21 9:57am
   
Thanks, for the reply.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900