0

How may I have a tag <a> to onclick go to a new page and POST something?

I have the code below:

<a href="#" onclick="cat_filter(1);">Cat Name</a>

And the function cat_filter()

function cat_filter(cat) {

    jQuery.ajax({
      'url': 'http://xxx/procurar', 
      'type': 'POST',
      'dataType': 'json', 
      'data': {cat: cat}
    });

}

PHP on URL page

$cat = $_POST['cat´];

What I neeed to do is to execute the function cat_filter() to pass the variable to a new URL as POST. How may I achieve this?

William
  • 1,010
  • 3
  • 21
  • 39
  • 1
    Possible duplicate of [navigate to another page with post request through link](http://stackoverflow.com/questions/17378619/navigate-to-another-page-with-post-request-through-link) –  Jun 26 '16 at 14:09
  • @Terminus, thanks you for the suggestion, but the question you marked as possible duplicate is not passing a `POST` to the new page. – William Jun 26 '16 at 14:13
  • 1
    Well sure the question isn't but the answer is ;) I like @gibberish's answer more than the accepted one over there anyway –  Jun 26 '16 at 14:19

1 Answers1

2

Ajax is a methodology for sending data to another PHP file without navigating away from the current page.

If you wish to send the data and also navigate over to the new page, you can do this:

function cat_filter(cat) {
  var myform = '<form id="ff" action="procurar" method="post">\
    <input name="cat" value="' +cat+ '" />\
    </form>';
  $('body').append(myform);
  $('#ff').submit();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<a href="#" onclick="cat_filter(1);">Cat Name</a>
cssyphus
  • 37,875
  • 18
  • 96
  • 111