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?
Related
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
});
So I have a form with a 3 hidden pre-filled input fields and 2 text input fields. I am trying to submit this form data using AJAX post as a JSON.
Upon hitting the submit button, I get the url as :
http:myurl.com:7001/pagename/?obj1=val1&obj2=val2&obj3=val3&obj4=val4
after this I wrote some code which I have mentioned to convert these as JSON and then post it.
The problem which I am getting is:
How can I integrate the code I mentioned into the submit button, so that, as soon as the user click the submit button, the url as mentioned above is obtained and everything else (as mentioned in the code) happens in the background and the ajax post request is made.
Thanks.
I am sorry if anything is unclear.
//This is the code, and If I run it in console after clicking the submit button then I am able to do the ajax post successfully. I want to integrate this code to the submit button.
var urlvalue = location.search.substring(1).replace(/\+/g, '%20');
var postdata = JSON.parse('{"' + decodeURIComponent(urlvalue).replace(/&/g, '","').replace(/=/g,'":"') + '"}');
console.log(urlvalue);
const URL = myurl;
$.ajax({
url:URL,
type:'POST',
data: postdata,
success: function(result){
console.log(result);
},
error: function(error){
console.log(`Error $(error)`);
}
});
I'm not sure I understand your question exactly, but if you just want the form submission to POST the data somewhere, you will have to provide a function to the form's onsubmit attribute.
That function should contain pretty much the working code you have at the bottom of your question (as well as cancelling the default form action with event.preventDefault()).
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
});
What is a good way of saving data form without submit button?
I have one idea. Below exemplary source code.
var delay = 1000,
timeId,
ajax,
//fw is some framework
form = fw.get('myform');
form.getFields().on('change', changeEventHandler);
function changeEventHandler() {
clearTimeout(timeId);
timeId = setTimeout(this.ajaxRequest, delay);
}
function ajaxRequest() {
//What do with old ajax request? Abort it?
ajax = fw.ajax({
url: 'ololo',
params: {
data: form.getValues()
}
});
}
What do with old ajax request? Abort it?
Have somebody other ideas?
I had a similar problem when designed an interactive form without save button.
First of all, its not a good idea to save the data on every change. I used on blur event, so when the input loses focus, I check if the value was changed (i.e. not just focus-blur on the input), if it was changed, I disabled the input and send an ajax request. When the request returned, I enabled the input once again (possibly displaying an error if the ajax failed and etc, depends on your needs).
Its the easiest way to do interactive form. This avoids the headache of multiple request trying to modify the same value on server side and the headache of monitoring all ajax requests.
.ajax() can send a post request and get data in return where as .load() can get any element in the rendered page. How to create a form when submitted(asynchromously) instead of getting back some data should get the page element of the rendered page that would be generated had there been normal submission instead of ajax submission?
I dont want to write views(Django) for xhr, normal requests separately. So, When I submit a form by ajax I dont want to hijack default action but only want to get some element of the rendered post submission page instead of actually being redirected to that post submission page which would have happened hadn't it been an xhr request.
Update:
load will do a POST rather than a GET if you supply the data to send as an object rather than a string. From the docs:
Request Method
The POST method is used if data is provided as an object; otherwise, GET is assumed.
So:
$("#target").load("/path/to/resource selector_for_relevant_elements", {});
..should convert the load from GET to POST. Of course, you'd replace {} with the arguments you want to send.
Original answer:
You can do the POST directly with ajax and then process the returned HTML yourself. For instance, to turn this load:
$("#target").load("/path/to/resource selector_for_relevant_elements");
..into a POST:
$.ajax({
url: "/path/to/resource",
method: "POST",
dataType: "html",
success: function(html) {
// Build the elemnts of the result in a disconnected document
var page = $("<div>").append(html); // See note below
// Find the relevant elements and put them in target
$("#target").html(page.find("selector_for_relevant_elements"));
}
});
I've done the wrapper div because that's what jQuery's load function does. You may want to look at the source for load (that line number will rot, of course, but the filename is unlikely to change) to see if there are other tricks you need to replicate.