My intention is to submit data from a form to the server and not have the page reload. It does not even need to display updated data. I am developing using Firefox and I'm looking at two paths to get what I want:
I've discovered that if I place a button inside a form, the form will be submitted with the name of the page containing it as a "GET" request. The form tag in this case has not method attribute and the action tag is empty. I can input the function that I want into the action attribute, and the browser will apply the rest of the form fields to the request. I find the formulation of the form convenient, but the browser goes ahead and replaces the page with whatever the response is from the server, taking me away from the original page.
Taking the button out of the form and wiring it exclusivly to a javascript function allows me to register a function to the onreadystatechange event. This has the effect of running a function rather than reloading the page when the server responds. The down side of this seems to be that it is necessary for the function to formulate the "GET" request on it's own.
It seems to me that there should be a way for the javascript function to tell the form to submit using it's own devices, and then be ready to process the the response. Being new at this I am unfamiliar with what "Best Practice" would be for this requirement.
You can just use a <button> to post your details.
function ajaxPage(postPage, paramList) {
xmlhttp.open("POST",postPage,false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(paramList);
return xmlhttp.responseText;
}
In this case your postPage is a address to a piece of relevant code and paramList is a list of & delimited name value pairs.
Kind regards,
Westie
You can add an "onsubmit" function to your form.
It is important to return false or call event.preventDefault() in that function in order to prevent the browser from posting the form.
HTML:
<form onsubmit="javascript:myFunction()">
...
</form>
Script:
function myFunction(evt) {
// do your ajax call...
evt.preventDefault();
}
Not really need the "Submit" you can search for autocomplete suggestions implementation with ajax:
Onfocus On..Even you will send all form data to server side, you you want autocomplete with server side response than it a pus and you can explain for the user for that you need.
This link may help you a bit.
This is what I've Ended up with, going forward with pathway number 2 as described in the original question, The button invoking the script is outside the form, so there is no submit event. Data from the form is harvested by the script as described in this answer to a related question:
https://stackoverflow.com/a/589100/747544
From there, the "get" request is formulated by the script
XMLHttpRequest.open("GET", "/myCommand?"+queryString ,true);
XMLHttpRequest.send(null);
The form is in effect "scanned" by the script without ever having been submitted, so there is no need to prevent the default behavior with an onSubmit event returning false. or preventDefault().
Related
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).
Im trying to track when a user hits the submit button on a contact form.
The page's URL doesn't change, its static.
I can't track a differnt URL after submission, the only option would be to track when a user hits the submit button.
Do I need to edit my analytics account?
Where do I add the additional javascript?
UA is installed correctly (analytics.js)
I'm new to GA and javascript so please break it down for me.
Thanks
I can't track a differnt URL after submission, the only option would be to track when a user hits the submit button.
That is a bit of a non sequitur. Even when the Url does not change there is probably some stuff happening - before you send it there is probably some form validation, and there is some action behind the scene to send there form, like e.g an ajax call.
You could attach event tracking to a submit handler:
<form onSubmit="ga('send','event','category','action','label')">
<input type="text" id="text" name="text">
<input type="submit">
</form>
However this would just tell you that somebody hit the submit button, not if they filled in the form correctly or if the form actually has been sent.
Now I enter speculation land, because I do not know how your form actually works - maybe you can show us an url or give more information.
But maybe you have a validation function that is called on the submit action of the form to see if the form is filled in correctly. In that case it would be advisable to do the tracking in the validation function (horribly simplified example, not production code):
<form onSubmit="validate()"><input type="text" id="text" name="text"><input type="submit"></form>
<script>
function validate() {
var test = document.querySelector('#text').value
if(test = "") {
ga('send','event','Form','Submit','Submitted, but not filled in');
return false;
}
ga('send','event','Form','Submit','Submitted with correct values');
return true;
}
</script>
That's a tad better, at least it tracks the difference between correct submissions and invalid submissions.
Even more speculation: If your form is sent without page reloads it uses probably an ajax call, and there is a huge probability that is uses jQuery (I say that because a) it really is probable and b) it's easier to construct an example in jQuery. The same can be achivied with other libraries or in native JS, but the example will produce an error if you do not use jQuery).
jQuery has a thing called "global ajax handlers". "Global" means they are not callbacks for a specific action, they hook into jQuerys ajax "mechanism" whenever a call to an ajax function is made. The following might work if you have only one aja event per page (else you need logic to distinguish the different ajax event e.g, by checking the url they are being send to), and allows you to track if the ajax call has returned successfully, like when your form data has been send to the server and the request return a 2xx status code:
$(document).ajaxSuccess(function() {
ga('send','event','Form','Submit','Yeah, form data sent to the server');
});
However this does not tell you if the data has been processed correctly. For that you need to make the server emit a success message and check the response:
$( document ).ajaxSuccess(function( event, xhr, settings ) {
if ( settings.url == "formprocessor.php" ) {
if(xhr.responseText.indexOf("success") > -1) {
ga('send','event','Form','Response Received','Form data processed ');
} else {
ga('send','event','Form','Response Received','Form data NOT processed ');
}
}
});
The global ajax event handler is attached to the document - you can put that anywhere on your page, it will do nothing unless an ajax event was called.
Again, this is not production code. Do not try to copy and paste.
This was certainly a bit much if you are new to this, but it should at least help you to improve the question and to see what kind of things are possible. If you can share an Url to your form I can possibly improve the answer.
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.
I have a form embedded in a web page. When the user clicks submit the XHR response is either a form with all fields reset (i.e. upon success), or a form with error messages (i.e. upon failure). I use the response to overwrite the existing form.
This works the first time the user submits the form. If they submit a second time however, the problem is that the form is posting a full HTTP request.
In the web page the form is wrapped in a span, #add-container. The button within the form is #add-button.
Per the code below, I am trying to re-bind a function to the click event of the buttom whenever the content in the span changes. It seems that this works the first time (i.e. when the document loads), but not subsequent times (i.e. when the XHR response is loaded into the page).
// Add product and services
$(document).ready(function() {
$("#add-container").change(prepareAddForm());
});
function prepareAddForm() {
var uri = '/product/add/org/4/format/html';
$("#add-button").click(function() {
$("#add-container").load(uri, {language: "php", version: 5});
return false;
});
}
Any ideas? Thanks for your assistance...
Sorry - just sorted it out. Needed to use the .live() method!
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