Stuck trying to display information from JavaScript form - javascript

Just working on a class project and I can't figure out what to do next.
I've got a form that is being validated with JavaScript. It's the usual information, name, cc# email, etc.
Well the only tuts I can find relate to how to get the form to validate in the first place, which I've already accomplished.
Now all I need to do is figure out how to get the information that I've captured to display in the confirmation page. I don't need any server side validation if that helps.
Here's a link to the page so far (http://sulley.dm.ucf.edu/~ph652925/dig3716c/assignment4/dinner.html)
Any pointers or references?

<?php
print_r($_REQUEST);
?>
will print whatever value the PHP callback is getting from your form.
=H=

You could try to use the GET parameters to forward the info:
link.to.new.page.html?param=value&param2=value2
etc...

It looks like you're using PHP. If you're sure you don't want any validation, of any kind, then the simplest way to output what was on the form (with some degree of control over what it looks like) is by using the POST global variable in PHP:
<?php
$firstname = $_POST['firstName'];
// etc etc for the other fields
?>
You can then output whatever you want by using those variables. The 'name' property for the HTML fields corresponds to what goes inside the square brackets in the PHP code above.

First, I would like to note that if you are using any server side application, you should absolutely validate the input on the server script before doing anything with it. The client side validation is really intended to make it easier for the user to enter the correct information and can be easily hacked or irrelevant if javascript is off... This said, on the client side, you could intercept the submit event, check the different field values. If you have errors, you display error messages, otherwise, you submit the form. example:
if we have this form:
<form action"myActionscript.php" method="GET" id="#myForm">
// form items here
</form>
and then this script (Beware, code not tested)
<script type="text/javascript">
var f = document.getElementById('myForm');
if (f.addEventListener) { // addEventListener doesn't work in ie prior ie9
f.addEventListener('submit', checkForm);
}else{
f.attachEvent('submit', checkForm);
}
function checkForm() {
// Check all input fields logic,
// you could have an errors array and add an error message for each
// error found. Then you would check the length of the error array,
// submit the form is the length is 0 or not submit the form
// and display errors if the length is > 0.
if (errors.length > 0)
{
// iterate through the array, create final error message
// and display it through an alert or by inserting a new
// DOM element with the error message in it.
// [...]
}else{
f.submit();
}
}
</script>
I have to say that the whole thing would be much easier and certainly more cross-platformed if you used a javascript library like jQuery... ;)

Related

Synchronous Requests Depreciated [duplicate]

I have a very complex form which contains multiple tabs. Each tab contains a unique Plupload instance (for uploading multiple images). The form allows a user to upload a medical image 'case' where each case is made up of multiple imaging 'studies' (e.g. CT scans) and each study contains multiple images.
When the user clicks the 'submit' button, I intercept the click with jQuery because I need to do the following:
Check the required fields are entered [easy]
Get a unique id number from my server. This id number is required by each Plupload instance to know which directory to upload to.
In my function called upon form submission I have the following code snippet:
var case_id;
// Code to check the required fields are entered
....
// Get the case id number from the server
$.get('ajax/unique-case-id').done(function(data){
case_id = data;
});
// do something with case_id and other things. MUST happen after the ajax call
....
// if there was a problem uploading the images, stop the form from submitting
if (problem_occured) {
return false;
}
With my current logic, I need the script to pause UNTIL it gets case_id. This was possible before jQuery 1.8 but the $.ajax() async : false property has been deprecated.
My question is two-fold:
Is there a way to hold up the script until I get the required case_id?
If not, any idea how I could change my logic to work around this?
You might be wondering why case_id is so important. The plupload instances do their upload before the form submits and they need a directory to upload to. I want the images being uploaded to go into a folder on my server called case_id. This will let the PHP script on the server figure out what to do with them once it gets the rest of the form POSTed data.
This is a very common 'problem' that can be solved pretty easily by using callbacks appropriately.
$("#submitButton").click(function (event) {
event.preventDefault(); //Don't submit the form, we'll submit it manually.
var case_id;
// Code to check the required fields are entered
....
// Get the case id number from the server
$.get('ajax/unique-case-id').done(function(data){
case_id = data;
// do something with case_id and other things. MUST happen after the ajax call
....
// if there was a problem uploading the images, stop the form from submitting
if (problem_occured) {
alert("something went wrong");
} else {
$("#referenceToTheForm").submit();
}
});
});
Long story short, keeping the "deal with problems or submit the form" inside of the callback to the $.get call will essentially cause the script to 'pause' until it gets the data back. Then you can use something like spin.js to give the user a good waiting experience until it's done.

JS/JQuery/PHP - How to echo errors on form validate failure, and jump to div on success?

I have a fixed-position form that can be scrolled out onto the document and filled out anywhere on the page. If they fail to fill out the form properly, the errors are currently echod out onto the form, which is the intended design for that aspect. What I don't currently know how to do is, if the form is completed and $errors[] is empty, to use jQuery scrollTop() to jump down to the bottom.
Could anyone help me out with this? Current javascript involved is:
$("#A_FORM_submit_button").click(function() {
$("#FORM_A").submit( function () {
$.post(
'ajax/FORM_A_processing.php',
$(this).serialize(),
function(data){
$("#A_errors_").html(data);
}
);
return false;
});
});
The PHP involved is simply
if (!empty($errors)){
// echo errors
} else { // echo success message} <-- would like to jump to div as well
edit-- for clarity: not looking to make the page jump happen in the php file, so much as return a value for the jq $.post function to check and then perform an if/else
I might be jumping the gun here but I believe your design is wrong which is why you are running into this problem.
The ideal way of handling form validation is to validate forms via Javascript and when users enter in their information you immediately show some indicator to ask them to correct it. As long as the validation is incorrect, you should not be accepting a form request or making any AJAX calls.
In the off-chance that they do successfully send the data, you should be doing a validation check via PHP as well which, if failed, would redirect to the original page with the form. From there you could do whatever error handling you want but ideally you would retain the information they entered and indicate why it was wrong (Javascript should catch this but I guess if it gets here the user might have JS off or your validation logic might be wrong)
If I understand correctly, it seems like you are doing your error handling with Javascript (that's fine) but showing the error via PHP. As Hydra IO said don't confuse client-side and server side. Make them handle what they need to handle.
Hope this helps.
#aug described the scenario very clearly.
In code it translates in something like this
$('form').submit(function(){
form_data = $(this).serialize();
if(!validate(form_data))
{
// deal with validation, show error messages
return false;
}
else
{
// Submit form, either via Ajax $.post() or by just returning TRUE
}
});
The validate() function is up to you to work out.

I need help finding an alternative to synchronous jQuery ajax

I have a very complex form which contains multiple tabs. Each tab contains a unique Plupload instance (for uploading multiple images). The form allows a user to upload a medical image 'case' where each case is made up of multiple imaging 'studies' (e.g. CT scans) and each study contains multiple images.
When the user clicks the 'submit' button, I intercept the click with jQuery because I need to do the following:
Check the required fields are entered [easy]
Get a unique id number from my server. This id number is required by each Plupload instance to know which directory to upload to.
In my function called upon form submission I have the following code snippet:
var case_id;
// Code to check the required fields are entered
....
// Get the case id number from the server
$.get('ajax/unique-case-id').done(function(data){
case_id = data;
});
// do something with case_id and other things. MUST happen after the ajax call
....
// if there was a problem uploading the images, stop the form from submitting
if (problem_occured) {
return false;
}
With my current logic, I need the script to pause UNTIL it gets case_id. This was possible before jQuery 1.8 but the $.ajax() async : false property has been deprecated.
My question is two-fold:
Is there a way to hold up the script until I get the required case_id?
If not, any idea how I could change my logic to work around this?
You might be wondering why case_id is so important. The plupload instances do their upload before the form submits and they need a directory to upload to. I want the images being uploaded to go into a folder on my server called case_id. This will let the PHP script on the server figure out what to do with them once it gets the rest of the form POSTed data.
This is a very common 'problem' that can be solved pretty easily by using callbacks appropriately.
$("#submitButton").click(function (event) {
event.preventDefault(); //Don't submit the form, we'll submit it manually.
var case_id;
// Code to check the required fields are entered
....
// Get the case id number from the server
$.get('ajax/unique-case-id').done(function(data){
case_id = data;
// do something with case_id and other things. MUST happen after the ajax call
....
// if there was a problem uploading the images, stop the form from submitting
if (problem_occured) {
alert("something went wrong");
} else {
$("#referenceToTheForm").submit();
}
});
});
Long story short, keeping the "deal with problems or submit the form" inside of the callback to the $.get call will essentially cause the script to 'pause' until it gets the data back. Then you can use something like spin.js to give the user a good waiting experience until it's done.

jQuery already submitted vs. being submitted

I'm working on a jQuery function that forwards form data to page without interfering with the normal submission. I can do it without any issues as long as I capture the submit using .submit(), but I would have to run my own validation on the data because it operates independently of the regular submission. Is there a way for jQuery (or any Javascript) to detect that form data has been posted and validated?
cheers,
Mike
Edit:
Workflow looks like this:
1. User enters data
2. Clicks submit
3. Site runs validation and accepts input
4. Submits data to new page
5. jQuery function detects new data was submitted and accepted so it runs.
More Edits for Clarity
I think you guys are missing the issue. I know how to detect a form is being submited (which is fine and dandy)
This is NOT what I want:
$(this).each(function(){
$(this).submit(function(){
*** Code ***
}
}
Suppose I have a validation script running independent of the code I am currently writing. How can I detect that this ran, and then go to the submit code above?
Use onsubmit="" on your <form> element, but return false. i.e.:
<form action="?" method="post" onsubmit="validate_and_submit(this);return false;">
The return false prevents the form from actually submitting so you can do stuff with AJAX.
Hope this helps!
What you need is AJAX here . So make a XHR request that goes to your server and posts data . The server's response would now go to a callback function ( your jquery function ) . If the data was validated and fine , you proceed further , else you stop .
What you are trying to do is not possible via the normal HTTP POST request .
EDIT: for the original clarification
If you want the server to only received validated data, then just make sure its not submitted to prior to the client-side validation occuring. You can do this with selectively calling event.preventDefault() based on the result of the validation.
$("#form").submit(function(event) {
//some stuff
if (validate(formdata) == false) {
event.preventDefault();
}
});
If you want a server to do the validation and submit to itself or another service, you should make that part of the server-side workflow. So it'd be like
1.) client submits to Service1
2.) Service1 validates
3.) Services1 submits to Service2 (such that service2 never receives code from elsewhere)

Pass data to database using javascript Onclick

I am a real noob when it comes to javascript/ajax, so any help will be very appreciated.
In reference to this question:
Updating a MySql database using PHP via an onClick javascript function
But mainly concerned with the answer left by Phill Sacre. I am wondering if someone could elaborate on how we are(if we can?) passing values/data through his example, using jquery.
The code example left by him is as follows:
function updateScore(answer, correct) {
if (answer == correct) {
$.post('updatescore.php');
}
}
...
<a onclick="updateScore(this, correct)" ...> </a>
Say for example, we are wanting to pass any number of values to the database with php, could someone give me a snippet example of what is required in the javascript function? Or elaborate on what is posted above please?
Thanks again all.
The simplest example I can think of is this. Make your AJAX call in your if block like this:
$.get('updatescore.php', {'score': '222'}, function(d) {
alert('Hello from PHP: ' + d);
});
On your "updatescore.php" script, just do that: update the score. And return a plain text stating wether the update operation was successful or not.
Good luck.
P.S.: You could also use POST instead of GET.
What you would do is on the php server side have a page lets say its update.php. This page will be visited by your javascript in an Ajax request, take the request and put it in a database.
The php might look something like this:
<?php
mysql_connect(...)
mysql_query("INSERT INTO table
(score) VALUES('$_GET["score"]') ")
Your javascript would simply preform an ajax request on update.php and send it the variables as get value "score".
Phil is not passing any values to the script. He's simply sending a request to the script which most likely contains logic to 'update' the score. A savvy person taking his test though could simply look at the HTML source and see the answer by checking to see what the anchor is doing.
To further nitpick about his solution, a set of radio buttons should be used, and within the form, a button or some sort of clickable element should be used to send the values to the server via an ajax request, and the values sent to the server can be analyzed and the status of the answer sent back to the page.
Since you're using jQuery, the code can be made unobtrusive as seen in the following example:
$('#submit_answer').click(function() {
var answer = 'blah' // With blah being the value of the radio button
$.get('updatescore.php',
{'value': answer},
function(d) {
alert('Your answer is: ' + d') // Where d is the string 'incorrect' or 'correct'
}
});
Enjoy.

Categories