Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send POST data and navigate with JQuery?

On my blog I have a lot of <pre> blocks containing code snippets.

What I want to do is add a .click() handler to all the <pre> elements on the page which will send its content to another page - let's call it viewcode.php - via POST.

I know how to send information to this page using $.ajax, I'm just not sure how to send the information and navigate to the page.

The idea is that visitors can click a <pre> which will navigate to another page containing the code on its own for readability and easy copy / paste.

I have a feeling the solution is dead simple and probably obvious, I just can't think of it.

like image 475
Marty Avatar asked Mar 22 '12 23:03

Marty


1 Answers

Not sure I would handle it this way, probably I would simply pop up a dialog with the code rather than leave the page, but you could handle this by building a form using javascript then triggering a submit on that form instead of using AJAX.

Using dialogs with jQuery UI:

 $('pre').on('click', function() {
      $('<div title="Code Preview"><p>' + $(this).text() + '</p></div>').dialog({
          ... set up dialog parameters ...
      });
 });

Build a form

 $('pre').on('click', function() {
      var text = $(this).text();
      $('<form class="hidden-form" action="something.php" method="post" style="display: none;"><textarea name="code"></textarea></form>')
          .appendTo('body');
      $('[name="code"]').val(text);
      $('.hidden-form').submit();
 });
like image 127
tvanfosson Avatar answered Sep 19 '22 01:09

tvanfosson