William William - 5 months ago 7
PHP Question

How onclick can post to a new page?

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?

Answer

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>

Comments