Passing form data with Ajax - javascript

I have a page which opens a thickbox of another page which contains a form within it. However, upon that form being submitted (it writes the data to the DB) I need the parent page of the thickbox to update certain rows of the form (the values that have been changed).
I have been reading online, but I have never really attempted doing anything like this with Ajax before (i just normally use jQuery load()). Essentially my theory is that I could use the jQuery .submit() funciton and have a callback function which takes the post values and passes them to the previous page. I am unsure however to pass the values from the form caught in the callback function to the previous page as the form although being shown on the page in a thickbox is a different page.
Any help would be greatly appreciated!
Just to help visulaise what the page looks like:
The form showing details is under the thickbox, and once the update buttons is clicked I would like to have a way of passing the new details back to that form without having to refresh the entire page.
Many thanks,

Well there are several ways you could do it one could be to find the div that the thickbox opens then find the iframe in there which would in theory show the returned data from the server depending on how you are returning it and then using jQuery you could extract the data and update the original page.
Another way would be to just retrieve the updated data manually through the main page on the onClose event of the thickbox which IMO is a waste of a call if the iframe returns it.
That all depends on how your server returns the data to the form though.

You can do two things, first you might want to use the form submit event to trigger an update of the form on the page:
$('#myThickboxForm').submit(function() {
// take the data in one of the form fields
var fieldInputData = $('#someThickboxFormField').val();
// now update the other form using this value
$('#pageForm').find('#aPageFormField').val(fieldInputData);
});
Your thickbox also triggers an "unload" event when it gets closes, you can listen to that event like this:
$('#TB_window').on('unload', someFunction);
var someFunction = function() {
// do something when the thickbox closes
}

Related

Setting window.top.location.href to a Form Submission

I'm working on application which uses iframe overlays in addition to its main window. One of these overlays is used to modify user settings, some of which affect the display of the main window. So after saving these settings I would like to update the main window so that the user can see their new settings in action without having to log back into the application, but I have yet to find a way that is both consistent and renders the updated main window correctly...
The specifics are that a click on the Save button calls a JavaScript function. This function submits an HTML form to invoke the appropriate Spring-MVC action (saveXXXSettings.do). In the corresponding server-side method (saveXXXSettings()), a post-save call to another method to redraw the main page will render an updated version of that page but within the iframe overlay instead of the top frame of the browser. So I just tried to set window.top.location.href to the form submisssion, i.e.,
window.top.location.href = settingsForm.submit();
and got an HTTP error page with no helpful information. In looking at this site and the W3 School page, I see that the default method-type for HTML forms is GET, so I'm wondering if the only way to get around my error to use the corresponding Spring action and a parameter string, i.e.,
window.top.location.href = saveSettings.do?formParam1=xxxx&formParam2=yyyy
I'm trying to avoid having to assemble a parameter string just to achieve the window-refresh I want, so any advice or suggestions are appreciated...
I would recommend using iframe event listeners instead. From the main frame add a listener to messages. Might look something like this...
window.addEventListener('message', function(e) {
var submitParamters = e.data;
});
Then when the user clicks submit in the overlay iframe, post a message to the main window. Might look something like this...
mainWindow.postMessage(submitData, targetOrigin);
You can read more about this here... http://blog.teamtreehouse.com/cross-domain-messaging-with-postmessage.
This is capable of performing cross-domain messaging, but will work with same domain as well.
Thanks for the answer, CurtisJD, but I decided to go with a different approach: I'm copying the values entered in the iframe overlay into a form on the main page, then I submit that form to save the values then refresh the home page, which it does automatically at the top (i.e., browser) level. Thanks again for your quick response...

Calling a Javascript function on focus of a page based on user interaction

I have a requirement where clicking on an icon should open a new window where the user will be able to view and edit certain fields. After the user closes this window and comes back to parent window, the icon color and text should be changed( for eg:- if the user has removed certain data, the icon will change to red color and text is set to null. If the user presses cancel button, nothing changes)
I am planning to implement this using a body onload function which essentially checks with the database using AJAX requests to see if the user has changed the data, then accordingly change the icon and text.
But, I see 2 problems in this approach
1. There will be a AJAX call even if the user has not changed anything.(ie. pressed Cancel button)
2. AJAX is called every time the body is on focus. Eg:- He may be working on some other page (or a different browser altogether) and comes back to this, resulting in an AJAX call.
Can anybody suggest a better approach.
I am using Javacript, JSP, Java
Two ways to implement this
Method 1
You know the methods which changes the database in the opened form. Suppose you have a delete method, write an additional window.opener.location.reload() after the method. The downside is that opener(parent window) gets reloaded every time you change something in the child window. Which is unnecessary.
Method 2 - Using cookies
I am using MDN's A little framework: a complete cookies reader/writer with full unicode support for creating cookies. The plan of action will be this. Create a cookie and set a value for it like this after you change anything in the child window and update it in the database like this docCookies.setItem("isChildFormUpdated", "yes");. You can use the same cookie for every action you do. Now when you navigate back to the parent form, do this.
$(document).ready() {
$(window).focus(function () {
var formCookie = docCookies.getItem("isChildFormUpdated");
if (formCookie !== null && formCookie == "yes") {
//resetting the cookie. you can also remove the cookie
docCookies.setItem("isChildFormUpdated", "no");
//docCookies.removeItem("isChildFormUpdated");
// your ajax call comes here
//or you could simply reload the form so that we get fresh data
//window.location.reload(); // it will be heavier
}
});
});
I hope you get the basic idea.
I think the easiest way to do this would be to set a cookie (learn how here). You can then have the two windows communicate between each other. This wouldn't be AJAX, but it will most likely work.
Another nice way to create a popup-like box is by using a modal box. These can be complicated but they look very nice. You have to make a jQuery plugin in, but you can take the one here and learn how it works. Good luck with your requirement.

Jquery ajax modal form post back to parent form

I have a query and don't know where to start - I have a image select input field on a form thats populated by an jquery ajax autocomplete. What I would like to do is the following:-
If a user wants to choose an alternative image that's not currently in the dB pop up a modal/lightbox form which contains the upload/editing form.
Once posted I want to pass this data back to the original form field and refresh the data for the autocomplete.
I already have the upload and editing forms working as standalone pages I just want to incorporate the output back into the original form.
Is it possible?
Can anyone suggest modal/lighbox script that can do this?
What data are you trying to retrieve in the parent window? Assuming your using an iframe in your lightbox? If you aren't then you should just be able to set variables and call functions from your upload script output as if it were the same page.
If you are...
I don't believe there are any lightbox/modal solutions that support this, I normally incorporate a script like below in my upload script so you can monitor the success/failure of the uploaded file and the data.
(function () {
parent.myClass.imageLocation = $output_your_image_location here;
return;
)();
You can obviously edit this to handle different situations but I always use the parent keyword as I have a similar way of handling uploads in some software I've built recently.

How do I add a callback function to .submit() in Javascript?

I am submitting a page onclick of a form element and need a function to run after the submit refreshes the page. I'm trying to add an animated scroll back to the clicked element that caused the submission. I've got the scroll part covered but I can seem to figure out how to cause the function I wrote for the scroll to run after the page refreshes from the submit.
Any timely help would be much appreciated!
If you are doing a full submit, rather than an AJAX submit, then the page that displays afterwards is not the same page as the one that the form was submitted from. Consequently, the identity of the clicked element will not be available on the second page.
What you need to do is, during the submit handler, store the identity of the clicked element (Should probably be a unique ID of some kind) in a hidden field of the form.
When the page refreshes, it should now have the unique ID available (Probably placed in the same hidden field of the form by the server side code) and a javascript function can read this value to control the scrolling.
Does this make sense?
If you update your question to include some sample code, then I might be able to clarify further.
If you do a "real" form submit, where the actual page refreshes, there is no way you can do it from the client (except using frames). Once you leave the page, your javascript is out of scope. You need to insert the javascript to the refreshed page on the server.
If, on the other hand, you are submitting the form and refreshing a part of the page via ajax, then, depending on the framework you use, you'll be looking for a callback hook like onSuccess etc. in your ajax submit function
This would be easier to do in ajax however if you need to do it as a postback then you need to attach an event to the body load event and send some data back with the postback that would identify that the page has loaded as part of a post back and not a new page load.
e.g. create a hidden contol ont he web page and on the postback give it a value , on the postback check to see if that hidden control has a value and if so run your scorll code.

Dynamically Refreshed Pages produced by Python

I've been researching this on and off for a number of months now, but I am incapable of finding clear direction.
My goal is to have a page which has a form on it and a graph on it. The form can be filled out and then sent to the CGI Python script (yeah, I'll move to WSGI or fast_cgi later, I'm starting simple!) I'd like the form to be able to send multiple times, so the user can update the graph, but I don't want the page to reload every time it doe that. I have a form and a graph now, but they're on separate pages and work as a conventional script.
I'd like to avoid ALL frameworks except JQuery (as I love it, don't like dealing with the quirks of different browsers, etc).
A nudge in the right direction(s) is all I'm asking for here, or be as specific as you care to.
(I've found similar guides to doing this in PHP, I believe, but for some reason, they didn't serve my purpose.)
EDIT: The graph is generated using Flot (a JQuery plugin) using points generated from the form input and processed in the Python script. The Python script prints the Javascript which produces the graph in the end. It could all be done in Javascript, but I want the heavier stuff to be handled server-side, hence the Python.
Thanks!
I'm assuming that you have two pages at the moment - a page which shows the form, and a page which receives the POST request and displays the graph.
Will a little jQuery you can do exactly what you want.
First add to your form page an empty div with id="results". Next in your graph plotting page put the output you want to show to the user in a div with the same id.
Now attach an onclick handler to the submit button (or to the individual parts of the form if you want it to be more dynamic). This should serialize the form, submit it to the plotting page snatch the contents of the id="results" div and stuff them into the id="results" div on the the form page.
This will appear to the user as the graph appearing on the page whenever they click submit.
Here is a sketch of the jQuery code you will need
$(function(){
// Submit form
// Get the returned html, and get the contents of #results and
// put it into this page into #results
var submit = function() {
$.ajax({
type: "POST",
data: $("form").serialize(),
success: function(data, textStatus) {
$("#results").replaceWith($("#results", $(data)));
}
});
};
$("form input[type=submit]").click(submit);
// I think you'll need this as well to make sure the form doesn't submit via the browser
$("form").submit(function () { return false; });
});
Edit
Just to clarify on the above, if you want the form to redraw the graph whenever the user clicks any of the controls not just when the user clicks submit, add a few more things like this
$("form input[type=text]").keypress(submit);
$("form input[type=checkbox], form select").change(submit)
If you'll be loading HTML and Javascript that needs to be executed, and your only reason for not wanting to load a new page is to preserve the surrounding elements, you could probably just stick the form in an IFRAME. When the form is POSTed, only the contents of the IFRAME are replaced with the new contents. No AJAX required either. You might find that the answers here give you sufficient direction, or Google for things like "form post to iframe".
I'd like the form to be able to send multiple times, so the user can update the graph, but I don't want the page to reload every time it doe that.
The general pattern goes like that:
Generate an XMLHttpRequest (in form's onsubmit or it's 'submit' button onclick handler) that goes to your Python script. Optionally disable the submit button.
Server side - generate the graph (assuming raw HTML+JS, as hinted by your comment to another answer)
Client side, XmlHttp response handler. Replace the necessary part of your page with the HTML obtained via the response. Get responseText from the request (it contains whatever your Python script produced) and set innerHtml of a control that displays your graph.
The key points are:
using XMLHttpRequest (so that the browser doesn't automatically replace your page with the response).
manipulating the page yourself in the response handler. innerHtml is just one of the options here.
Edit: Here is a simple example of creating and using an XMLHttpRequest. JQuery makes it much simpler, the value of this example is getting to know how it works 'under the hood'.
Update img.src attribute in onsubmit() handler.
img.src url points to your Python script that should generate an image in response.
onsubmit() for your form could be registered and written using JQuery.

Categories