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

Utilizing Angular2 Observables for Time Interval Tracking

I'm working on a function that needs to be triggered every 500ms. My current approach in angular2 involves using intervals and observables. Here's the code snippet I've implemented so far: counter() { return Observable.create(observer =&g ...

Ways to modify the color of the legend text in a HighChart graph

Click here I am attempting to modify the color of the series legend text from black to any color other than black: $(function () { $('#container').highcharts({ legend: { color: '#FF0000', backgroundColor: '#F ...

The Express application remains silent unless a port is specified for it to

Having recently started working with Node, I encountered an issue with Express. My application is only listening to localhost:PORT and I want it to also listen to just localhost. Here is the code snippet: ** var app = require('../app'); var debu ...

Error: The function **now.toUTCString** is not recognized and cannot be executed by HTMLButtonElement

While the JavaScript code runs smoothly without setting a time zone, I encountered an error when trying to display the Barbados time zone. The issue is related to now.toUTCString function throwing the following error message. How can I resolve this? Uncau ...

Tips for sending information to an Express API through AJAX

While working on a website using Express and EJS, I encountered an issue with calling an API via AJAX. The problem arises when passing two values to the AJAX data upon button click, resulting in errors. Despite trying various solutions, I'm still stru ...

Creating a Timeout Function for Mobile Browsers in JavaScript/PHP

Currently, I am developing a mobile-based web application that heavily relies on AJAX and Javascript. The process involves users logging in through a login page, sending the data via post to the main page where it undergoes a mySQL query for validation. If ...

Putting a Pause on CSS Transition using jQuery

I am attempting to delay a CSS transition for an element by using a delay function, with an additional 0.2s applied to make it slide 0.2s later than the initial delay of the main wrapper. I am applying a class to give it a transition effect to slide from r ...

Having trouble retrieving a hidden value in JavaScript when dealing with multiple records in a Coldfusion table

In this table, there is a column that allows users to select a predicted time. <cfoutput query="getReservations"> <tbody> <td><input class="form-control predicted" name="predicted" id="ReservaTempoPrevisto" placeholder= ...

methods for converting an array to JSON using javascript

Our team is currently working on developing a PhoneGap application. We are in the process of extracting data from a CSV file and storing it into a SQLite database using the File API in PhoneGap. function readDataUrl(file) { var reader = new FileReade ...

What are some ways to ensure that the promise from postgres is fulfilled before moving forward with my code execution?

I am currently developing a Node-js application that requires retrieving information from the database before making another database call. However, I am facing an issue where the first check is not always resolved before proceeding to the next step. I hav ...

Creating a sleek navigation bar and sliding feature within the header of your Ionic 2

I am looking to create a sliding header for my website where the gallery hides and the navbar moves to the top as I scroll down, similar to the gif provided. Any help or ideas on how to achieve this would be greatly appreciated. Thank you. https://i.sstat ...

Functionality of the Parameters Object

As I transition from using the params hash in Rails to learning Node/Express, I find myself confused about how it all works. The Express.js documentation provides some insight: 'This property is an array containing properties mapped to the named rout ...

Does the first Ajax call always finish first in the order of Ajax calls?

In my code, I have an ajax call that triggers another ajax call based on its return value. The URL parameter of the second call is modified by the output of the first one. These two calls are interrelated as the first call feeds the URL parameter for the s ...

Retrieve an HTML document from a specified URL using JavaScript AJAX methods

var $ = require('jquery'); $.ajax({ type:"GET", dataType: 'html', url: 'http://www.google.com/', success: function(res){ console.log(res); } }); The error displaying in the console is: XMLHttpRequest cannot lo ...

Tips for Waiting for Binding in an Angular 1.5 Component (No Need for $scope.$watch)

Currently, I am in the process of developing an Angular 1.5 directive and have encountered a frustrating issue related to manipulating data that is not yet available. Below is a snippet of my code: app.component('formSelector', { bindings: { ...

Issues arise with the functionality of Zurb Foundation 5 tabs

Utilizing the tabs feature in ZURB Foundation 5, I've noticed that clicking on a tab changes the hash in the URL. However, I actually want to prevent this behavior as I rely on the hash for managing page loads. Although I attempted to use preventDef ...

Is there a way to dynamically load a file on scroll using JavaScript specifically on the element <ngx-monaco-diff-editor>?

I've been attempting this task for over a week now in Angular without success. Would someone be able to provide guidance? The onContainerScroll() function isn't being triggered, and I'm considering using JavaScript instead. How can I achiev ...

Experiencing consecutive errors while using the "wait_on_rate_limit" parameter

To prevent any rate limit errors, I implemented the parameter: wait_on_rate_limit into my function: api = tweepy.API(auth,wait_on_rate_limit=True,wait_on_rate_limit_notify=True) Initially, everything was working smoothly. However, when I exceeded the r ...

Display all items on page load using ng-repeat checkboxes in AngularJS filter

I have encountered a problem with filtering checkboxes in my code. I want all products to load on the page initially, and then when I check multiple checkboxes within technologyArray and/or technologyArray2, the products that match the checkbox name should ...

The AngularJS price slider may exceed its range if the ng-model is null or below the minimum value

I currently have an rz-slider featured on my webpage that is utilized for gathering the price of a product from the user. In addition to the slider, there are two input fields present which are designated for storing the minimum and maximum values. The ng- ...