Can I intercept form submit data to use with AJAX? - javascript

I have a Django app that shows a list of items in a selection item. When the user changes the selected item, I use AJAX to insert a form (using Django's Form and formset helpers) into a "content" section on the page to edit that item's data.
What I would like to do is, when the user clicks a "Save" button on the form, a Javascript function sends the POST data as though the form had been submitted, and then uses AJAX again to reinject the new data from the page.
I want to maintain a clean URL at all times, but always return to the entry you were editing (hence the AJAX HTML replacement).
I would prefer not to have to grab all the form fields and reconstruct a string that my Django Forms will recognize correctly.
Is there a way to do this? Am I going about the whole thing wrong?

To grab whole form and send it using AJAX on submit do something like this (assuming jQuery):
jQuery('form').submit(function (event) {
event.preventDefault();
var form = jQuery(this);
var data = form.serialize();
jQuery.post(form.attr('action'), data, function(html) {
...
});
});

Related

node.js & jade - making a post request and displaying the results in the same page without redirecting

I have node.js express web application which performs the CRUD operations on a button click. Here I need to update a record based on the input from the user. For this, I need to input the detail from the user, display the existing values of the record in the same page, and prompt the user whether he wants to change the data.
If yes, then I need to input the values from the user and update it. Is it possible to have this in a single jade file where I am getting the input values from user.
jade file :
extends ../layout
block content
.page-header
h3 Updation
form.form-horizontal(role='form', method='POST')
h4 Enter the employee id for which you want to update the details
input(type='hidden', name='_csrf', value=_csrf)
.form-group
label(class='col-sm-2 control-label', for='empid') Emp ID
.col-sm-2
input.form-control(type='text', name='empid', id='empid', autofocus=true)
.form-group
.col-sm-offset-2.col-sm-2
button.btn.btn-primary(type='submit')
i.fa.fa-pencil
| Get details
I have this file where I am getting the employee id from user and making the post request. I am not sure how to render the response to this same page itself and prompt for changing details.
Any help would be appreciated.
Yes, you can do this, but not with a form that gets submitted, because then your page is gone.
Instead, you can insert a button into your page that does an AJAX request to the backend, and on return of the AJAX request, you can dynamically replace some parts of your page with the returned data. Of course, you can include any data the user has entered into the AJAX request.
Since you want this all to happen in the frontend, you cannot do this in Jade. Instead, you need to add a script into your page that does what you want in the client's browser.
Here is an example of how to achieve this:
Put this in a file called ajax.jade:
mixin ajaxFunction
script.
function changeState(url, buttonid) {
$.ajax({url: url}).done(function (data) {
$('#' + buttonid).parent().html(data);
});
}
mixin ajaxButton(id, url, buttonLabel)
a.btn.btn-primary.btn-xs.btn-block(id='#{id}',
href='javascript:changeState(\'#{url}\', \'#{id}\')') #{buttonLabel}
Now you can put this mixin anywhere on your page. (Make sure the button id is unique across the whole page and does not contain spaces!). On click, it will replace itself with whatever the backend returned:
include ajax
+ajaxButton("myButton", "/some/url", "Klick me!")
Not sure if there's a way that the jade egine can partially render the jade template, If there is one way to do that, normally you can use Ajax to do this.
Form add submit event listener, in which you can set event.preventDefaut() to stop default submit process, in this way you can prevent page reloading.

html form save temp data

Hello guys I need your advice on best solution to my problem....
So I have simple html form which has input boxes, selects and stuff...
One of my select field generates its options from database an when user selects any option 3 input fields are filler automatically, problem is if value does not exist I have option value to create new. If user select this option javascript redirects to a new page where new option can be created and saved to database, after that user is redirected back to form however all fields that input fields have been filled now are empty....
What is the best way to save all input values user have entered so I can navigate user to different page where he can add item to the database and redirect him back to same form and fill all fields back?
First thing that I thought to put all input values to array and using php function http_build_query() send via GET and on redirection back send same array back, but form has like 20 fields and i believe it is not best solution as sending data take server resources...
Second, Put everything to json temp file, save on the server redirect user and on redirection back get this json file and fill data back and delete file afterwards... (I like this idea most)
Third, to create hidden form (like lightbox) show this form if needed, but here comes problem on this form submit it has to redirect somewhere if I redirect to same or different page I still lose all data...
Any idea guys?
In this case will better to use popup box (lightbox). Fill it with additional form and add event handler to it on form submit. Try to use event.preventDefault() inside the handler, then attach jquery.post method:
$( "#additional_form" ).submit(function( event ) {
event.preventDefault();
$.post('post.php', $('#additional_form').serialize());
$(#lightbox).hide();
});
There's a lot of ways to do it, you can also just serialize it without sending. Or append it to your main form.
Use the given codes
$("#additional_form").submit(function(event) {
event.preventDefault();
$.post('post.php', $('#additional_form').serialize());
$(#lightbox).hide();
});

Wanted to hide the parameters on javascript form submit?

My URL looks like the below format:
http://hostname:8080/search/?N=4294967292&Ntt=abcdef&add=1&Nr=AND(OR(a:abc,a:def,a:ghi),OR(b:abc,b:def,b:ghi));
I am submitting a form through javascript submit. I wanted to hide the Nr parameter value while submit the form.
My piece of code below:
$(".apply-btn").click(function(){
var nr=loadQuery();
var submitUrl = window.location.href;
submitUrl=submitUrl+nr;
$('#myForm').attr('action',submitUrl);
$('#myForm').submit();
});
any help on this..?
You can't.
You are asking the user's browser to send data to a server. The user can inspect that data.
The closest you could come would be to make a POST request instead (by submitting the form with the data in actual form fields instead of generating a custom action via JS). The information would still be visible in the Net tab of the developer tools that come as standard in most browsers these days.
create a hidden field in the form with the name Nr
set the value of the hidden field to the value of nr (instead of appending nr to the URL)
set the method attribute of the form to POST
set the action attribute of the form to the value of window.location.href
submit the form
Well you could use a POST request plus SSL to encryp your requests. As Quentin said, this also would not stop the user from seeing your request with the developers tool bar, but during the submission it is encrypted.

How do I get the data submitted from a form with JQuery?

How can I get the data that is submitted from a form with jQuery?
I know I can bind the submit function to the form
$('form').bind('submit',function(){});
and I know I can serialize the data in the form:
$('form').serialize();
But how do I get the data that was actually submitted from the form? Like if there are two submit buttons, I want to know which one was pressed. If I handle the submission with PHP I can do that, but ideally I want to get a copy of the submitted data, then return true so that the form goes on to be processed by PHP normally.
Thanks!
The pressed submit button should be available in the serialized field list - and the other submit buttons shouldn't be in there.
However, apparently jQuery does not add submit buttons in there (testcase). See http://forum.jquery.com/topic/submit-event-serialize-and-submit-buttons-get-the-button-name for a workaround.

How can 2 Html forms share 1 hidden field?

I have a page with 2 forms and a hidden field that is outside of both of the forms.
How can the hidden field be submitted with either of the forms?
I thought about doing something like this with jQuery:
<script type="text/javascript">
$(function() {
$('form').submit(function() {
// do something to move or copy the
// hidden field to the submitting form
});
});
</script>
Will this work? Any other ideas?
EDIT
The hidden field stores a serialized object graph that doesn't change. Both server methods require the object. The serialized object string can get pretty hefty, so I don't want this thing sent down from the server 2 times.
You can simply inject a copy of the element into each form right before submission.
This way, you can have the option of having different information for each hidden form field without affecting the other.
Something like this:
<script type="text/javascript">
$(function() {
$('form').submit(function() {
$("#hidden_element").clone().appendTo(this);
});
});
</script>
If you want to use the exact same element for both forms without creating a fresh copy, just don't use clone()
See documentation for clone() and for appendTo()
EDIT:
If you don't want to send the hidden element with every request the form sends. Consider storing it in the database for that user for that time. You can submit its content once, and once only for every page reload, and then just send the database id of the hidden element with each form post.
On page load, something like this:
$.post("page.php", { reallyBigObject : $("#hiddenfield").val() }, function(insertedID){
$("#hiddenfield").val(insertedID);
});
Then, in the server side code:
//insert $_POST["reallyBigObject"] into databse
//get the just inserted id (in php it's done with mysql_insert_id())
//echo, or print the just inserted id, and exit
This way your js gets the callback.
Now, you can submit the form as you would, but this time, you're only sending the id (integer number) to the server.
You can then simply delete the object from your server (run a cron to do it after X amount of time, or send another request to delete it.
Honestly, though, unless you object is HUGE(!!), I think storing it by submitting it only once is a lot more complex to execute than to simply send two requests to the server.
Let me know if you have any other questions...
With HTML5, you can include a "form" attribute with an input element. The value of the form attribute is the id of the form(s) the field belongs to. To include the field in more than one form, include all form ids in a space-delimited list. Unfortunately, the form attribute is not supported in IE at all (as of IE 9). FF and Chrome support start in version 4 and 10 respectively.
Append the field to both forms at page load:
$(function() {
$('#form1, #form2').append($('input[name=fieldName]'));
});
Assuming you are doing a non ajax submit you could just append the field into the form being submitted. However if you need this info in both forms is it not better to store this value server side in a session store. This way any non js clients will also work!
$(function() {
$('form').submit(function() {
$('input.yourhiddenSubmit').appendTo(this);
});
});
The only way to pass the variable to the next form is to have that variable in the data that is passed when the form is submitted (either GET or POST), unless you want to use AJAX. Assuming you want to have the hidden variable outside of the actual form for a "good reason", I would recommend using jQuery to include the hidden input field into the form just before submission, like so:
<script type="text/javascript">
$(function() {
$('form').submit(function() {
$(this).append("<input type='hidden' name='hiddenField' value='"+$("#hiddenField").val()+"' />");
return true;
});
});
</script>
Replace all the instances of "hiddenField" with the ID of your hidden field outside the form. This will create a new input inside of the form just before it is submitted with the value of the hidden field that is elsewhere on the page.
Beyond that, you'd have to be a bit more specific about what your exact problem was (and why the field isn't being included in the form) for me to help.
Note that the above code should work in theory, but I didn't have a chance to actually test it out myself.

Categories