habenah habenah - 1 month ago 8
HTML Question

Having 2 pages, How to change the content of a second page by a click event on a button in the first one?

Here is my problem,
I have a page called page1 (I have a button in this page to access another page called page2).
I want to change the content of a specific selector in page2 by a click event on the button of page1.
Here is my code for page 1 in pug

form#abandonForm(name='btn' action='page2')
button#abandonBtn.button Abandonner

Here is my code for page2 in pug


and here is my .js file

$( document ).ready(function() {
var $abandonBtn = $('#abandonBtn');
$.get('page2', null, function(data){
var $data = $(data);
$data.find('#termineExam').text("section changed");
console.log($data.find('#termineExam').html()); // print the changes
console.log(data); // print the same data without changes on the section


I don't understand why changes are applied on the DOM but not on the page2 itself.
Thank you for helping and sorry for my English!


You seem to misunderstand how jQuery.get() works.

From the docs:

jQuery.get( url [, data ] [, success ] [, dataType ] )

Returns: jqXHR

Description: Load data from the server using a HTTP GET request.

Basically, you are getting the content from 'page2' as a string and storing it in a variable named data. This is a one way street. When you call $data.find('#termineExam').text("section changed"); you are modifying the local variable not the actual page2 file

When you navigate to page2, you are requesting a brand new copy of the page2 file without any of the modifications that you applied to that string over on page1.

If you want to actually modify the content of page2, you'll need some sort of server side script (like php) that accepts new data from page1 and updates the page2 file.

Alternatively, if you just want to send some data to page 2 and have that data appear when that page loads, there are many ways you could do that.

One option would be to use localstorage:

Make a file called storage.js with the below content and include this file in both page1 and page2

 * Feature detect + local reference for simple use of local storage
 * if (storage) {
 *    storage.setItem('key', 'value');
 *    storage.getItem('key');
 * }
var storage;
var fail;
var uid;
try {
  uid = new Date;
  (storage = window.localStorage).setItem(uid, uid);
  fail = storage.getItem(uid) != uid;
  fail && (storage = false);
} catch (exception) {}
/* end  Feature detect + local reference */

In page1 do this:

$(document).ready(function() {
  var $abandonBtn = $('#abandonBtn');
  $abandonBtn.click(function() {
        storage.setItem('termineExam', 'section changed');

Then, in page2 do this:

$(document).ready(function() { 
        var text = storage.getItem('termineExam');
        if(text) $('#termineExam').text(text);