JS: delay onClick function execution until a page refresh occurs

Currently, I am working on a WordPress site that involves a form submission process. Upon successful submission, a new post is created.

After the user submits the form, I have implemented JavaScript to prompt them to share a tweet with dynamically prepopulated content. However, I encountered an issue where the tweet is preloaded with the content from the previous form submission instead of the current one.

I am considering delaying the onClick function until the page reloads with the updated content published. However, I am unsure about how to achieve this.

Below is the markup for the form submit input:

<input onclick="tweetIt()" class="exclude btn-main stack" name="user-submitted-post" id="user-submitted-post" type="submit" value="<?php _e('Submit', 'usp'); ?>">

Once the form is successfully submitted, the content is displayed as follows:

<p id="dream"><?php echo substr(the_title('', '', FALSE), 0, 140); ?></p> // the title is populated with one of the fields from the form

Here's the relevant JavaScript code:

function tweetIt () {
  var phrase = document.getElementById('dream').innerText;
  var tweetUrl = 'https://twitter.com/share?text=' +
    encodeURIComponent(phrase) +
    '.' +
    '&url=' +
    'http://xxx';

  window.open(tweetUrl);
}

I hope I have explained the situation clearly. Any assistance would be greatly appreciated!

Answer №1

To determine if the current request is a post, you can check this documentation and then proceed to tweet.

<?php 
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
?>
(function(){
  var message = "<?php echo substr(the_title('', '', FALSE), 0, 140); ?>";
  var tweetUrl = 'https://twitter.com/share?text=' +
    encodeURIComponent(message) +
    '.' +
    '&url=' +
    'http://xxx';    
  window.open(tweetUrl);
})()
<?}?>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize a single JavaScript file to handle various views without encountering errors due to undefined functions

My backend editing requires a single JS file. However, I face the challenge of needing different sets of methods for view A and view B — never both at the same time. To streamline this process, I combined all the jQuery functions for both views into one ...

Are the orders of events maintained when emitted using an event emitter?

I have a simple query regarding the event emitter, which is crucial for my program's logic. Currently, I am utilizing an external library that triggers events that I'm listening to. These events consist of 'data' and 'error'. ...

Using TypeScript to call Node.js functions instead of the standard way

Can someone assist me with the issue I'm facing? I have developed a default node.js app with express using Visual Studio nodejs tools, and now I am attempting to call the setTimeout function that is declared in node.d.ts. The code snippet in question ...

Does applying a style to an element that already has the same value result in a decrease in performance? Alternatively, do all browsers simply overlook it?

Assuming I have an element with the style top: 5px, and then I execute element.style.top = "5px";, will the browser readjust its position and trigger a layout again? Or does it recognize that there is no need to change anything? (Is this behavior specified ...

steps for extracting only the tweet content and saving it in a json format

Currently, I am engaged in a project that involves using the Twitter API to collect tweets related to various keywords within specific longitude and latitude ranges. After extracting the tweet data, I noticed that each keyword's dataset consists of di ...

Getting started with Babylon.js using npm: A step-by-step guide

I recently posted about my struggles with setting up Babylon.js using npm on Stack Overflow. Since I haven't received any answers yet, I was hoping to rephrase my question: Can someone provide a detailed step-by-step guide on how to set up Babylon.js ...

I am not getting any reply in Postman - I have sent a patch request but there is no response showing up in the Postman console

const updateProductInfo = async (req, res) => { const productId = req.params.productId; try { const updatedProduct = await Product.findOneAndUpdate({ _id: productId }, { $set: req.body }); console.log("Product updat ...

Having trouble with your JavaScript regex not functioning properly?

I am currently working with an array of arrays and I need to iterate through it to retrieve each word, excluding any "@", punctuation, and hashtags. However, my regular expression seems to be removing certain words entirely from the array and I can't ...

How can I retrieve a specific key from a nested array while using ng-repeat to iterate through it

I have successfully created a code snippet that retrieves JSON data and displays it in HTML using AngularJS. <div class="activity" ng-app="stream" ng-controller="streamCtrl"> <ul ng-repeat="x in myData"> <p class="au ...

What is the best way to add permissions to each role in JavaScript?

I have been attempting to dynamically add data to an HTML table using JavaScript. The data consists of roles and their corresponding permissions, which are retrieved using Laravel's ORM. I have tried utilizing a nested each jQuery function to append t ...

Issues persist with AngularJS integration using Modernizr

Incorporating AngularJS and Modernizr, I aim to identify media queries and trigger a function whenever the window or viewport is resized. My goal is to control element visibility based on whether the user is on a desktop or mobile device - certain elements ...

Receiving Request URL from XMLHttpRequest in PHP

I'm currently facing a dilemma as I work on a JavaScript script that is responsible for sending data from one of my forums to the server where a PHP script runs. The goal is to have the PHP script determine which JS output should be generated based on ...

Determining the top element displayed in a div: A guide

Looking for an answer on how to determine the top visible element while scrolling? You may find some insights in this post: (Check if element is visible after scrolling). My scenario is slightly different - I have a scrollable div containing multiple ele ...

HTML list with clickable elements for querying the database and displaying the results in a <div> element

Patience please; I am a newcomer to StackOverflow and this is my inaugural question. Struggling with writing an effective algorithm, I wonder if my attempts to "push" it forward are causing me to complicate what should be a straightforward concept, or if i ...

Is a component updating an unregulated text input to be controlled?

Whenever I attempt to input information into the form and save it in the state, I encounter the following issue: Warning: A component is converting an uncontrolled text input to a controlled one. Input elements should not transition between being contro ...

Creating a menu with items and listeners from a kmllayer - a step-by-step guide

Currently, I am working with a map that includes a kmllayer. This layer has been added using the following code: ctaLayer = new google.maps.KmlLayer('http://www.npd.no/engelsk/cwi/pbl/en/aFactGlobe/disc/ActivityStatus_Producing_labels.kml'); ...

React-Bootstrap Table Toolkit Encounter Search Import Issue

I encountered an issue while trying to integrate React Bootstrap Table into my project, resulting in the following error message. Uncaught ReferenceError: arguments is not defined at Object../node_modules/react-bootstrap-table2-toolkit/lib/src/search/Sea ...

Issue with background image resizing when touched on mobile Chrome due to background-size property set to cover

My current challenge involves setting a background image for a mobile page using a new image specifically designed for mobile devices. The image is set with the property background-size: cover, and it works perfectly on all platforms except for mobile Chro ...

Is there a way to update a child component in React when the parent state changes, without utilizing the componentWill

I am currently working on developing a JSON editor using React, but I am facing an issue with the library I am utilizing not having a componentWillReceiveProps hook. As someone relatively new to React, I am trying to find a way to automatically update th ...

Can you help me with sorting asynchronous line points for KineticJS?

For the past couple of days, I've been grappling with a peculiar issue that I found difficult to articulate in the title. The challenge I'm facing involves a KineticJs Line, which contains an array of points (line.attrs.points) represented as ob ...