简体   繁体   中英

JS; prevent onClick function from happening until page reloads

So I have a wordpress site I'm building that allows a user to fill out a form, and if successfully submitted, it will create a post.

When the user hits submit on the form I have some js that prompts them to send out a tweet with dynamically prepopulated content. The problem is that I want the the tweet to be prepopulated with the content of one of the fields they just filled out and submitted. But, because this happens immediately the tweet ends up prepopulating with the content from the last time the form was filled out.

So, I'm thinking if that onClick function can not fire until the page reloads with the new content added and published, that should work, but I'm not sure how to do that.

Here's 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'); ?>">

Here's how it is displayed once the form has successfully been submitted:

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

and here's the js:

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

  window.open(tweetUrl);
}

Hoping I've been able to articulate in a way that makes sense. Any help is, as always, greatly appreciated!

You can check if the current request is a post and then call tweet.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM