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.
Related
I have created a form in php which has to fetch data from table1 and dump it into table2 every time user clicks on a link (link provided in a different page). I have written code in a php page (assume eg -> test.php) including html as well. I tried submitting the form onload of the page using Javascript (document.formname.submit) but it keeps on going in an infinite loop and keeps inserting data in table2 again and again.
How do I prevent this and auto form submit only once and still stay on the same PHP (i.e. test.php) page, which also contains the code for displaying detail view of the inserted data in table2?
That's because simply calling submit() on a form fill cause a full page reload. If you want to keep the current approach, you should instead use AJAX call to submit the data from that form.
Read here for more details. The article explains how to do both GET and POST requests using JS.
That sad, your solution seems somewhat ... emm ... hairy. Why exactly are you copying data from no table top another?
Before JavaScript check this condition by using form name.
if ( ! isset($_POST['main']) )
Here main is form name.
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
}
I want to show a acknowledgement (more precisely a popup) when form is successfully submitted.Previously I was using Ajax to validate form and display pop up but now I want to achieve same without Ajax.
Is there any event in javascript/Jquery which is invoked after successful form submission? or Is there any other alternative available?
Thanks!
EDIT 1 :
I am using Spring 3.0.
Here is the detailed scenario
1. User fill the form and click on submit
2. Request will be sent to controller (Server side)
3. Validation will be done at server side
4. If errors are present I am using Spring validation to show it and goto Step 1
5. else successfully submit the form and show a popup.
6. After user clicks on popup redirect to other page.
EDIT 2:
I am completely agree with the opinion that Ajax is the right/best way to do it and I already implemented it using Ajax. But client want to use non-ajax approach and I cannot go beyond his words.
This question piqued my curiosity, as I was trying to do something similar using the iframe solution suggested by Leon. Eventually I succeeded, however, I would like to suggest that rather than using a direct onload property, you make use of the jQuery .load() event on the iframe.
Edit: So here's how I set up the form (using HTML5, so quotes aren't necessary):
<div id=message></div> /* Example-specific, see below */
<form method=post action=backend.php target=iframe>
// Form data here
</form>
<iframe name=iframe></iframe>
I added the following CSS code to hide the iframe:
iframe {
border:0px;
height:0px;
visibility:hidden;
width:0px;
}
Don't use display:none, as some browsers will refuse to submit to an element that's not displayed.
Then in my $(document).ready() JavaScript...
$('iframe').load(function(){
// Your load event here.
});
You could also change that about, so that it specifically only triggers after a specific event (if you're using dynamic forms, for example). In such a case, you may want to use .unbind('load') before .load() to prevent previously-added .load() functions from calling.
Now when the form is submitted, it loads into the hidden iframe. When the iframe loads the page (backend.php, in my example), it triggers the .load() function. In my specific case, I set up a <div id=message> to display a message:
$('iframe').load(function(){
$('#message').html('The form successfully submitted.');
});
Without Ajax? No Problem - let's go back to how the Web really used to work in the past ;-)
Since I am getting you don't want to refresh the current page, how about this approach:
have a hidden iframe on the same page, with a name & id
point the target property of your form to the name given in the previous step
submitting the form will now be "hidden"
you can have an onload property on the iframe set to a javascript method of your liking to get called once the form finished submitting
that javascript code could also retrieve the contents of the iframe and check for your server-side response (maybe even including an error msg)
notify the user about the result
This is all fairly easy to setup, let us know how it works for ya..
I am not sure which language you are coding in.
One option - use javascript.
On the submit button onclick event (client side event), perform the page validation and display alert pop up, if the page is valid.
<script type="text/javascript">
function OnSubmitClientClick() {
Page_ClientValidate();
if (Page_IsValid) {
alert('Form has been successfully submitted.');
return true;
}
}
</script>
Why do you want to drop AJAX approach? Without AJAX, server side validation implies page reload. On page reload you would lose client side (JS) state.
One alternative is to use hidden frame/iframe/a new window to perform server side validation on form submit(possibly use the pop up you are referring to in your question). Which in my opinion is not the right approach(A BIG NO). You may rather stick to AJAX or go with non AJAX way of form submit.
I've seen good posts here of bits and pieces of what I am attempting to do, but nothing with all areas addressed. Does anybody have any code examples or advice to help me do what I am trying to do?
First, I will build my MVC view with an array of data such as (org name, id, status) where status is a boolean value, either selected or unselected. However, rather than showing a mere checkbox, I'd like to display a particular showing either a green (selected) or red (not selected) button based on the state of the database value. CSS is not an issue.
Then, if and when a user clicks the button, I would like to change the div value from red to green (or vice versa), but also update the boolean value in the database field via an AJAX call. It would be preferable to leverage JQuery where possible.
Finally, I need to know how to do this all using CodeIgniter. I am well versed in CI but a Javascript/JQuery newbie - deer in the headlights at this point. Can anyone point me in the right direction or suggest a web site with some sample code close to what I am trying to do or a good resource other than the obvious? Thank you kindly.
OK, so CodeIgniter is a PHP framework - which means it works server-side. (I know, there's an ajax library in there, but I don't use that.) We have to understand the difference between server-side and client-side. Your javascript is client-side. I usually develop everything without javascript to begin with in codeigniter, then go back and add the javascript bits. This helps me to ensure that the system works for those that don't have javascript turned on, or can't execute javascript for whatever reason. (BTW, this is called progressive enhancement).
So, first, let's take care of the non-javascript version:
You just need to give your red/green button a url when clicked that points to the controller method that will update the database record and redirect you back to the page that you were previously on (which has the red/green buttons).
/controller/method.html is our controller method that will save to the database and redirect back to this page. -->
Check
Now, let's take care of the js version:
in your view, you just need to hijack the click, send the ajax request, and change the red/green button based on the result from the controller method. So, what we do is keep the link from redirecting the page to the href attribute (e.prevendDefault()). Then, we get the value of the href and make an ajax call to that controller method. The method will determine if this is an ajax request and save to the database, then echo back a "success" message. On success, we can update the visual component on the client side.
$('.my-button').live('click', function(e) {
e.preventDefault();
$.ajax({
// $(this).attr('href') gets the value of the links href attribute
// which is "/controller/method.html" in this case
url: $(this).attr('href'),
success: function(data) {
// update your button with whatever html to write the new button
$('.my-button').replaceWith('Check');
}
});
});
Your controller method just checks if it is an ajax request or not. If so, just returns success, if not redirects the page.
function my_controller_method()
{
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
$_SERVER['HTTP_X_REQUESTED_WITH']=="XMLHttpRequest") {
// update your database
echo "success";
}else{
// redirect back to page
redirect($_SERVER[‘HTTP_REFERER’]);
}
}
What you want is sort of a thumbs up / like thingy...there's a demo included in the link http://www.geertdedeckere.be/lab/themeforest/thumbsup/demo/
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.