Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery onclick pass post variables and reload page

Can I pass post variables and reload a page on clicking an hyperlink?

To be clear I have something like this. <a href="test.php?name=test">Click</a>

If javascript is enabled,

I think I can use "event.preventDefault()" to suppress passing as GET variable.

So now onclick, name should be passed as post variable instead of get.

If javascript is disabled, Then the above should work.

like image 369
user277891 Avatar asked Feb 21 '10 00:02

user277891


2 Answers

You could do it, by creating a new form element, pointing it at the href and calling .submit() on it.

<a class="postlink" href="test.php?name=test">Click</a>

<script type="text/javascript">
    $('.postlink').click(function() {
        var form= document.createElement('form');
        form.method= 'post';
        form.action= this.protocol+'//'+this.hostname+this.pathname;
        $.each(this.search.slice(1).split(/[&;]/g), function() {
            var ix= this.indexOf('=');
            if (ix===-1) return;
            var input= document.createElement('input');
            input.type= 'hidden';
            input.name= decodeURIComponent(this.slice(0, ix));
            input.value= decodeURIComponent(this.slice(ix+1));
            form.appendChild(input);
        });
        document.body.appendChild(form);
        form.submit();
        return false;
    });
</script>

Or you could just do an AJAX request instead and reload() the page afterwards if you prefer.

However, I'm not sure why you'd want to do this. What use is a link that's usually POSTed, except when it's not? (Not just when JS is disabled/unavailable or when it's a search engine, but also when the user middle-clicks the link or tries to right-click-bookmark it or whatever.)

If all you want is something that behaves like a button to submit a POST form, better to actually use a real form and submit button, and then use CSS to restyle it to look like a link if that's what you want it to look like.

like image 148
bobince Avatar answered Nov 12 '22 16:11

bobince


Very good hint....

I was first trying to send the form data via an Ajax Post call and reloading the page afterwards, but it was not working properly:

var  biq_select_val = jQuery('#biq_search_select').val();
jQuery.post(window.location.href,
        { biq_amazon_item_list_search: biq_select_val},
        function() {window.location.reload();}
    );

Now I am using just a:

jQuery('#biq_amazon_item_list_search_form').submit();

and it is working fine.

like image 40
Christian Gnoth Avatar answered Nov 12 '22 16:11

Christian Gnoth