jQuery onclick pass post variables and reload page - javascript

Can I pass post variables and reload a page on clicking an hyperlink?
To be clear I have something like this.
Click
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.

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.

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.

I have some 10 links on a page. When user clicks on those links ajax-reload must take place.
To be clear I have something like this.
one
Two
If javascript is enabled,
Onclick, ajax load must take place.
If javascript is disabled, Then the above should work.
Basically I am using name to limit some values of my search page.

Related

Switch from iframe "AJAX" to proper AJAX

This is legacy code.
I'm working on a project where we're using iframes to simulate AJAX.
Basically, we're using the target attribute to submit the <form> in an iframe, resulting in the request not opening a new tab. Also, we echo a <script></script> in the response from the PHP, and the result is executed since it populates the iframe.
Here's an example of such <form> :
<form id="form_to_submit" method="POST" action="ajax/createUser" target="iframe_name">
<input type="text" name="input_to_send">
<button type="button" onclick="$('#form_to_submit').submit()">Submit With Onclick!</button>
</form>
Nowadays, not only this looks evil, but it has one (perhaps others) huge pitfall. If one request is made through this process, and the client goes somewhere, and then goes back in his browser history, it'll send the request again.
To fix this last problem, there are many solutions. I think the one I prefer the most is to use real AJAX instead of iframes. Now, in theory, I could change every single form in the source code to make it use AJAX, but I know I won't have 1 straight week of work just for this purpose.
I'm looking for a "quick" way to intercept these requests before they're sent to the iframe, and send them with AJAX instead.
So far, I tried to target <form> tags which have a target="iframe_name" and listen to the submit event to then send the request again with a same method/URL/data.
$('form[target=iframe_name]').on('submit', function (event) {
event.preventDefault(event);
var url = $(this).attr('action'),
datas = $(this).serialize();
$.post(url, datas).done(function (response) {
eval($(response).text());
});
});
But that only works if they're submitted through a real click on a submit button. I'd say 95% of these cases are submitted through onclick tags which will .submit() the forms, and in these cases, the submit event won't trigger it appears.
I'm stuck, any idea ?
Note : I'm tagging jquery only to let you know it's available to be used, even though the question is still relevant with any lib/framework of JS.
You can actually remove the onclick attributes just by doing a general jQuery action on document ready:
<script>
$(document).ready(function() {
var getButton = $('form').find('button');
getButton.prop('onclick',null);
// put listener script here for new form submit (using ajax)...
});
</script>
This piece of code just does a general lookup on the page for all forms, finds the buttons, then removes the onclick attribute. Once you do this the form should not submit anymore with that inline javascript.
I would suggest this be temporary as you incrementally change the forms over time to natively work using the jQuery listener (like the other 5% of forms you have created with no onclick).

prevent multiple submission with button

I am currently viewing all the possibilities for preventing multiple submission with button tag. The problem I am facing is that if users click submit button really fast it will enable them to submit multiple posts. I would like to restrict the submission to just one submission. I tried to use onclick="this.disabled = true, but it makes the button not working at all. The current button tag looks like this:
return "<button class='button btn btn-primary' id='gform_submit_button' onclick='this.disabled = true' type='submit'><span>Submit!/span></button>";
Can anyone guide me as to how to achieve this?
Ultimately, you cannot prevent multiple submissions on the client-side. You would have to implement these security measures on the server-side, in whatever server-side language you are using (e.g., PHP).
On the client side, you could do something like this
var canSubmit = true;
$('.button').click(function(){
if(canSubmit)
{
// fire missiles
canSubmit = false;
}
else
{
// sorry missiles loading
}
});
Now since after clicking once canSubmit has been set to false, a second click would not run the code. After validating or processing your submitted data you can set canSubmit back to true.
When the button is onClicked call this function:
function submitFunc(formId){. document.getElementById(formId).submit();
}
Submitting a page is always going to be tricky. There are two challenges with submit
As you rightly mentioned that user can submit same page multiple times
After submitting page if user refresh the page then also page is going to be resubmitted
There is one trick to handle this challenge redirect the page with GET call. The GET call which you have used to load the data. Read more about it here.
So I would recommend to redirect page to GET once form is submitted.
In this process the new form will be loaded and if user try to submit the form validations will be fired that will handle 1st challenge.
And due to redirect as your last call is GET on refresh data will be loaded and there is no harm in it.

Submit Form in DNN, typical answer not working

I am trying to submit a mailchimp form from within my DNN (DotNetNuke) site. Typically, you just remove the form tags and put some javascript in the onclick event of the submit button...like here. This works and you can see as such here.
But, I am using this popup module, as I want this form to pop up when someone comes to the site. And in this configuration it does not work. It will submit the form to the designated URL, but no form data is passed. This page is here.
A couple of observations:
When you view the page source, the popup form is within the form tags, yet a this.form returns null in the script.
When you inspect the submit button element in Chrome, you see that the html form is then OUTSIDE the form tags.
So maybe there is some javascript with this popup module that is moving the DOM element on page load???
I created a js function to call on the input button submit; code is as follows:
function submitSubscription(clickedElement){
$form = $('body').find('form');
$form.attr('action', 'http://InciteResults.us2.list-manage1.com/subscribe/post?u=6d82b6a028c94cc75005eb4fe&id=1c7ceabac4');
$form.submit();
}
Note: in this function clickedElement.form is returning null.
Because your content is not in a <form>, you're going to put it inside a <form> in order for your script to work. You can either dynamically create a <form> element, or move your content back inside the main <form> when you submit. Try something like this:
function submitSubscription(clickedElement){
var $form = $('<form></form>', { action: 'http://InciteResults.us2.list-manage1.com/subscribe/post?u=6d82b6a028c94cc75005eb4fe&id=1c7ceabac4' });
$('#mc_embed_signup').wrap($form);
$form.submit();
}

Javascript code not running after the page is refreshed or reloaded

I have a javascript code that, whenever a checkbox is checked, will reload my current page and then is supposed to grey out some input fields.
However, it is only doing the reload when the page is reloaded the input fields are never greyed out.
$(document).ready(function(){
$("#storePickUp").on("click", function () {
if ($(this).is(":checked")) {
document.getElementById("shippingForm").submit();
document.getElementById("shippingAdress").disabled = true;
document.getElementById("shippingState").disabled = true;
document.getElementById("shippingCity").disabled = true;
document.getElementById("shippingZip").disabled = true;
document.getElementById("shippingZipCode").disabled = true;
document.getElementById("shippingButton").disabled = true;
}
});
});
So in your code on the 4th line where you call .submit()... unless you have some extra magic on the page that you are not showing, this line will proceed to post/get your form to whatever url you have configured in that form.
What this means is that the lines underneath that do not matter at all, since they will not be executed on the forms target page.
To get around this if you truly need the form post in the middle, you would need to post to a specific url and use that url as a trigger on page load to disable those elements. Not directly after the click, but rather on the newly loaded page that is the target of the form... make sense?
I think that's because it's only disabling them when you click on #storePickUp but if your page is reloaded it will reset.
Method submit is executed, page reloads, code after submit is never executed. Even if that code would be executed, page refresh nullifies any changes.
You should probably do submitting with ajax, not with submit method. If you are using jQuery, it will make it easy for you:
http://api.jquery.com/category/ajax/

redirecting to next page

I wrote a javascript function to go to a particular page if it came from a particular page.
Function:
function proceed()
{
if( document.referer == "http://abcd.com/index.php?action=SignUp")
{
return document.location.href = "http://abcd.com/editprofile.php?action=editprofile";
}
}
Submit button for a form in current page(b):
What i want is to go through a sequence of pages a->b->c , where a is previous , b is current , and c is next in my case. b has a form, on submitting values to the form, it should also call the javascript function and then go to the page c.
Can anybody help me find out where is the mistake? Any help would be highly appreciated. Thanks.
Since you have a form I guess there's also some php/cgi script that will handle the form's data!?
In that case your form won't continue to that script if you override your submit button via javascript in such way that it loads another page (other cases like validation do work that way, of course).
So
Your submit button has spaces next to the onclick attribute: onclick = "javascript... should be onclick="javascript....
Your function proceed() should return true for the submit to perform.
Even after all syntax correction, there's still something odd. After all, you can only give one "next page" functionality to your submit button. So what should the form call:
your php or cgi script? Then you can build a redirect to page "c" into that one.
your page "c"? Then what do you need the form for?
both, but independently? In that case I suggest a javascript popup from proceed() displaying page "c" and returning true so the form continues with its script.
To be more accurate you will have to provide more of your application's code.
Solution seems to be the following. Use the submit attribute for your button:
<button type="button" onclick="proceed(); alert('You are not authorized to execute this action!');">Click Me!</button

Categories