How to catch GET request url from form submit - javascript

I have a quite complicated HTML form. This form sends a GET request to the server. On submit event I would like to catch this GET URL and send it like an ajax request. But don't know how to get this submit URL.
I would like to have it in pure JavaScript and not with jQuery. I tried to do it via:
addEventlistener('beforeunload', function(e) {
e.preventDefault();
var getUrl = location.href;
});
The problem with this code is that it is not triggered by form submit, and I don't know if location.href is a good idea.
How could it be done?

Use an event listener on the form's submit event.
document.querySelector("#yourform").addEventListener('submit', function(e) {
e.preventDefault(); // block the default GET request
let url = this.action;
// rest of code for sending AJAX request to url
});

Related

Update page from POST response

Is there any way to preserve the default behavior of a form POST submit action in a javascript http request? Normally when I submit the forms, the url is redirected to the action and the page is replaced with the response html, but if you use preventDefault() or return false on a submit event you will get the response in HTML sent as a string to the callback.
Right now I have to add some extra data to my form submission, but I would like to update the page based on the response.
$("#"+target).on('submit', function (e)
const counselors_list = counselors.list.map(e=>e.name);
const groups_list = ...
const data = $(this).serialize() + "&" + $.param({patient: {counselors: counselors_list, groups_attended: groups_list}});
$.post(action, data, e=>e)//Data gets returned as e, instead of updating the page
return false;
});
The only way I can think of is replacing the whole DOM with the response, but that seems very hacky. Is there any way to preserve the default form behavior while still adding this data?

How to submit a form using a link, not a submit button?

I have a form which is sending data to another script with AJAX post. Idea is to change this to GET, so I can submit form or trough form input where user click "Submit" or just hit "Enter", and form data is passed with AJAX to another script, and data is returned to origin script.
What I want is to make user able just to type parameter in url, like whois.com/domain.com, and just hit enter, so my form can be autopopulated with data in url and submitted, so my JS can be trigerred to make AJAX call.
<script>
$('#form1').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'GET',
url: 'check.php',
data: $(this).serialize(),
success: function (data) {
//console.log(data);
$('#response').html(data);
$("#myModal").modal();
}
});
});
</script>
Idea: Check if $_GET['variable'] is set in url yoursite.com?domain=domain.com, and then pass variable to form, and submit form by code?
You could use location hash instead of query string. For example, you can use format: http://yoursite.com/#domain=domainname.com
Then, you can register hashchange event listener, and in event handler you can extract domain and pass it to ajax function.
window.addEventListener('hashchange', function(ev){
doNewAjaxRequest(location.hash.replace('#domain=', ''));
});
Or, if you are using jQuery:
$(window).on('hashchange', function(ev){
doNewAjaxRequest(location.hash.replace('#domain=', ''));
});
Or, you can use just domain name after the hash, as: #domainname.com
$(window).on('hashchange', function(ev){
doNewAjaxRequest(location.hash.replace('#', ''));
});
Now your users can type different domain, and when they press enter, you can handle the change.
*Keep in mind that anything after the # is not sent to server in url, but you can access and use it from javascript.

ajax form validation before submit how?

I am doing ajax cross domain request to my php page on server.
I am posting form from html via ajax to my php page on server.
Have problem with validation in client side.
I don't know how to do validation in client side before send form.
html form is standard form, posting input fields: name, last name, message....
My html form, client side:
<script type="text/javascript">
var output = $('.nesa');
$(document).ready(function(){
$("#form1").submit(function (e) {
e.preventDefault();
$.ajax({
url: 'http://www.example.com/form.php',
crossDomain: true, //set as a cross domain requests
type: 'post',
data: $("#form1").serialize(),
beforeSend: function (){
// add spinner
$('.spinner').append('<img id="animacija" src="spinnersmall.gif" alt="Loading" />');
},
success: function (data) {
$(".nesa").html(data);
alert("sent " + data);
},
error: function(){
output.text('Message is not sent!');
}
});
});
});
How to to validation? I try to put code in beforeSend but without success.
Or maybe to use submitHandler?
Idea is when user click submit, that validation start, and if fails to tell "insert your email address". Now when i click submit it send data to server. I want that first check input fields.
This form is actual working it sending data to server, but just need to figure out how to do validation. Where to put validation in ajax call?
Thanks
Create a function to validate form which return true/false. Call the function just before the $.ajax. check if return is false then return.. see the example below...
if(!validateForm())
return false;
First, are you actually using an AJAX form?
You explained that you load the form itself via AJAX, but do you send it that way, too? It looks to me that you're trying to send it the HTML way. You can hook into the click event of the send button before you send the form. However, since the button is added to the page at runtime, you need to register the event to document.
$(document).on('click', 'input[type=submit]', function() {
// Validate form
// Add error message on fail, and return
// Else submit form via AJAX
});
In either case, you can use jQuery's blur event as an alternative to validate each field when the user jumps to the next. You could even validate every time the user presses a key with keypress.
I always validate them right before I enter them into an AJAX call. Here is my exampel
$('#form_nieuwsbrief').bind('submit',function(){
var name = $('input[name=naamNieuwsbrief]').val();
var email = $('input[name=emailNieuwsbrief]').val();
var proceed = true;
if (name==""){
$('input[name=naamNieuwsbrief]').css({'border':'2px solid red'});
proceed = false;
}
if (email==""){
$('input[name=emailNieuwsbrief]').css({'border':'2px solid red'});
proceed = false;
}
if(proceed == false){
$("#msg").append("<div class='alert alert-danger' role='alert'>U bent informatie vergeten in te vullen.</div>");
setTimeout(function(){
$('.alert').fadeOut(400, function(){
$(this).remove();
})
;},10000
);
}
if(proceed == true){ // make the ajax call
This is just a quick one for a newsletter that just requests name and email. But the principle is the same. Just before you make an ajax call, create the if else statement with a variable you set if something is false. else you stick it tot he original validation, thus you can proceed.
Please validate the form before sending ajax request. If there is no error then ajax request should be send otherwise return false.
You can do like:
$("#form1").submit(function (e) {
e.preventDefault();
// Get the Login Name value and trim it
var name = $.trim($('#name').val());
// Check if empty of not
if (name === '') {
alert('Text-field is empty.');
return false;
}
});
You can see the demo Here's (http://jsfiddle.net/LHZXw/1/)
You can also make a function onKeyup.
You're already validating via server side correct? Why don't you use that same validation rules to appear like your client side - via Ajax. I have a tutorial on how to do that:
http://michaelsoriano.com/how-to-ajax-validate-forms/

ajax form data pass before the page reloads

I use a jQuery.get() request to send a form data. But often the page reloads/redirects too fast, before my JavaScript/jQuery code catches and sends the form data to where i need. I use alert() to get the ajax request done while the user clicks ok on alert. Now i need the form working as usual (with PHP post and redirect) and to send the form data using jQuery or JavaScript BEFORE the page reloads and NO alerts. Is there any elegant way to make the page wait until jQuery is done with the request (without using alert)?
jQuery('#form').live('submit', function() {
var inputValue = jQuery(this).find('#theInput').val();
jQuery.get('http://someurl.com/order?var=' + inputValue);
//alert('an unwanted alert');
});
UPD: I embed jQuery code through Google Tag Manager's iframe. So I can't change the way the form works. And I shouldn't prevent the form from submitting.
jQuery('#form').live('submit', function(e){
e.preventDefault(); // prevent default behaviour
var inputValue = jQuery(this).find( '#theInput' ).val();
jQuery.get('http://someurl.com/order?var=' + inputValue, function(){
// redirect
});
//alert('an unwanted alert');
});
I would take a look at [done][http://api.jquery.com/deferred.done/] which could probably do what you want it to do. .done() will wait for the entire ajax to finish, and then run whatever function you call within done.
You can bind callback to do redirect and return false; to prevent default redirect shown as below:
jQuery('#form').on('submit', function() {
var inputValue = jQuery(this).find( '#theInput' ).val();
jQuery.get('http://someurl.com/order?var=' + inputValue,
function(data){
//write redirect code here. In case if you want to check response, you can get it in data variable.
});
return false; //prevent default redirect action
});

Firebug not showing the response from jquery form plugin post submit

I am usinh jquery form plugin with this code
$(".form1").live('submit', function(e){
$(".form1").ajaxSubmit(options);
});
Now i see that firebug console shows all ajax requests so that i can see the request and response.
But i have seen that when i use the above code then my ajax request is completed but i can't see any post request in console.
But if i use
$(".form1").live('submit', function(e){
var queryString = $('.form1').formSerialize();
$.post('/book/create/', queryString);
Then i can see the request response
i want to know why is that
Only ajax requests (XMLHttpRequest) are shown in the console. Use the net panel to debug all other requests.
But .ajaxSubmit() is indeed an ajax request as the docs say
ajaxSubmit
Immediately submits the form via AJAX.
In the most common use case this is
invoked in response to the user
clicking a submit button on the form.
ajaxSubmit takes zero or one argument.
The single argument can be either a
callback function or an Options
Object.
The problem may be that you're not preventing the actual form submission in your code .
$(".form1").live('submit', function(e){
$(".form1").ajaxSubmit(options);
return false; // this will prevent the actual form submission.
});

Categories

Resources