I have an issue regarding sending form values to a script. I have a form set up, and upon the user pressing a button I want the values in the form to display on another part of the page. I can easily do this with php or another web scripting language, but all I know is how to do this by sending it to the script in a form of
http://www.example.com/myScript.pbp?value1=VALUE
is there a way to do this without loading a new page? Like just show a loading overlay on the page until the script completes and displays the value on the page?
I'm guessing this would be accomplished using Javascript or Ajax or something like that.
If anyone could help me out, or even just say where I should start to look, I'd really appreciate it!
Indeed. Just attach an onsubmit event listener to your form that always returns false to prevent actual sending of your form via the usual GET or POST request.
In your event listener you can send the form values using XMLHttpRequest and let the callback function update the relevant part(s) of your page.
But remember to always create a fallback option (with the usual GET or POST request of the form) to handle your form in case JavaScript is not available (e.g., turned off, blocked, etc.).
Yes AJAX would be exactly how you would do it. Have a look at the tutorial over at Tizag: http://www.tizag.com/ajaxTutorial/index.php
That will get you started in no time at all.
If you just want the values in the form to display on the page again without any interaction with the server then something like jQuery would be the best approach.
Jquery has a nice form plugin that you can do the following:
var form_values = $('#form_name').formHash();
the form_values will then be a hashed array of your form values in the system i.e.
<form id="test">
<input id="test1" name="test1" type="text" value="Test Text"/>
</form>
So form_values['test1'] would hold the value Test Text in it
Once you have the values you could then use some other jquery functions to display them on the page i.e.
<div id="displayDiv"></div>
then your javascript could be
for (key in form_values) {
$('div#displayDiv').append('<div>Key: ' + key + ' Value: ' + form_values[key] + '</div>');
}
This would put your values in the display div
Here is a simple javascript ajax object. You can use without loading any library.
Related
My classmates and I are building a small submission form in which a user submits shipping and billing information for their order.
The two main factors that effect the order price are the type of shipping the user selects ( $shippingType ) and the price of the item ( $initialPrice ). The variable $totalPrice is then defined which adds $shippingPrice and $initialPrice.
What we are working towards is having $totalPrice update when $shippingPrice is changed without the user having to resubmit the form. Can this be solved using php? Or would we have to use a jquery event to update the page in realtime.
You'll want to use some sort of jQuery as mentioned above. It's important to understand that PHP is only used either in AJAX, or before the page has loaded. Meaning you cannot use PHP on a page that has already been loaded. To change elements after it's loaded you would need to use javascript/jquery of some sort. I've attached a quick fiddle to illustrate an example of what I think you're looking for.
The gist of it is that you would bind a change event so that when the elements you want to use for mathing are changed you can update the other items.
$('#shipping').bind('focus, change', function() {
//Get the inital value of the #cost input
var initial_val = parseInt($("#cost").val());
//Value from the #shipping input
var additional = parseInt($("#shipping").val());
//Parsed ints because '+' is used for concatination as well, so making the vars ints will make '+' go back to math.
$("#cost").val(initial_val + additional);
});
No it's not the prettiest, but it works.
Here's the Fiddle:
http://jsfiddle.net/Lb486ck8/2/
You will have to use Javascript to accomplish this behavior. Furthermore, you will need to use AJAX (Asynchronous Javascript And XML) to make it work. AJAX is a way for Javascript to send requests to a web page "behind the scenes" while your page stays in the foreground.
http://api.jquery.com/jQuery.post/
I am writing code for a small webproject using js and jquery. In it, at some point, onclicking a button, i create a dialog. the dialog has a form within it with a name field and some number fields. I am supposed to check user inputs and send them to server, along with appending the name field to a list in the browser, to intimate user, one more item has been added. Two strange things are happening -
1) After posting the form, the dialog box closes on its own without me issuing a dialog('close') anywhere in the submit button handler.
2) The name entry doesn't get appended to the list. Its as if the whole page refreshes after the submit. With the original default entries of the list of names.
Anyone has any ideas on why this is happening? Would post some code for your aid.Please don't suggest to use Ajax instead. I think this reflects some fundamental flaw in my understanding of JS ways and would like to clear it first than just switching to some other technology.
<div id='dialog' title='Define New Matrix'>
<form name='form1' id='form1' method='post'>
<fieldset>
<label for="Name">Name</label>
<input type='text' name='nameofmatrix' id='Name' class='whitepanes'><br>
<label for="a11">a11</label>
<input type="text" name='a11' id='a11' class='whitepanes number-field'><br>
<label for="a22">a22</label>
<input type="text" name='a22' id='a22' class='whitepanes number-field'><br>
<button id='submit_button'>Submit</button>
<button id='cancel_button'>cancel</button>
</fieldset>
</form>
<p id='tip' style='color:red;'><i>All fields are required</i></p>
</div>
<script>
//#button_define is a button on whose clicking the dialog opens.
$('#button_define').click(function(){
$('#dialog').dialog('open');
$('#tip').html("<p style='color:red; font-size:small'>All fields are mandatory</p>");
});
$('#submit_button,#cancel_button').button();
$('#cancel_button').on('click',function(){
$('#dialog').dialog('close');
});
$('#submit_button').click(function(event){
event.preventDefault();
var name=$('input[name=nameofmatrix]').val();
//Validate is a function which returns a bool if validation proceeds correctly
var isCorrect = Validate();
if(isCorrect){
//if validated correctly then add to list
$('#form1').submit();
//$('#dialog').dialog('close');
$('#selectable').append("<li class='ui-widget-content'>",name,"</li>");
}
});
</script>
Its as if the whole page refreshes after the post. with the original entries.
That's precisely what happens. Though I'm not sure where you're submitting the POST request to since there's no action attribute on your form. But a standard non-AJAX request triggered by a form sends the request to the server and then renders the response from the server. If the response is this same page again, then this same page will be rendered again.
JavaScript isn't going to remember the state of the previous page when it loads this new response. Even if they're the same page, they're two separate responses from the server. So...
1) After posting the form, the dialog box closes on its own without me issuing a dialog('close') anywhere in the submit button handler.
The dialog isn't closing. After the page refreshes you're in an entirely new page context. It didn't close, it just hasn't been opened yet in this context.
2) The name entry doesn't get appended to the list.
There's nothing that would cause this to happen when the page loads, so in the new page context it doesn't happen. Your server-side code would need to include this content in the response to the POST request.
I think this reflects some fundamental flaw in my understanding of JS ways and would like to clear it first than just switching to some other technology.
Included in that misunderstanding is the fact that AJAX is part of JavaScript. (The "J" in "AJAX" stands for "JavaScript.") It's not "switching to some other technology." It's taking advantage of the capabilities of the technology you're already using. All AJAX does, really, is send requests and receive responses to/from the server without refreshing the page context.
You are not properly appending the name. The concatenation operator is not a comma, but a + in javascript:
$('#selectable').append("<li class='ui-widget-content'>" + name + "</li>");
Next, the form refreshes because you are submitting the form using $('#form1').submit();. If you do not want the page to refresh while submitting, use ajax.
So not sure if this is possible but I have a pretty complex form. With multiple levels of processing ie: If you click a radio button 'x' amount options so up in a drop down etc etc.
Well the problem I have is all the form fields need a name, and went I submit the form I'm sending alot of junk. IE Url could be '?meat=3434?fruit=34495?salad=034943' you get the idea. But in the end all I'm looking to is pull the 'salad' value into the url without all the other byproducts. IE: '?salad=034943'
I've tried a few things, pulling all the inputs radios etc out of the form and placing them in a div. The making a form with just a hidden value so I can pull through Mootools (But that made conflicts because I'm using Mootools Form.Validator so then that fails) Then I tired to make two forms, One that would just be all show, then I would pull the value I want into the processing form. Which I thought would work but apparently it still will process both forms.
Any ideas/techniques of how to accomplish this would be greatly appreciated! (because I'm losing my mind)
Disable any form field you don't want sent and it won't show up in the URL.
In HTML it's:
<INPUT type="text" name="foo" DISABLED>
In javascript set document.forms[...].elements[....].disabled = true.
If you hide the field with CSS it will still be sent like normal.
the elegant way you do this is mount your GET url to submit by yourself..
this way you can send only what you want..
dont send any junk.. you can have problems in the future with a variable that you didnt know you were sending..
you can use this util function of jQuery
var params = { width:1680, height:1050 };
var str = jQuery.param(params);
// str is "width=1680&height=1050"
I am having trouble validating a long form that is loaded via AJAX after the document is loaded. Using the standard validation syntax, the validator looks for my form in the document before it exists and therefore gives me an error:
$(document).ready(function(){
$("#mainForm").validate();
});
firebug responds with:
nothing selected, can't validate, returning nothing
I tried putting the $("mainForm").validate(); in a function then calling the function with the onSubmit event from the form but no luck:
function validate() {
$("mainForm").validate();
};
----------
<form id="mainForm" onSubmit="validate();">
...
</form>
Thoughts?
Some additional info for #Chris:
I have a page that is dynamically creating a form based on many different modules. The user picks the module(s) that apply to them then the form updates with that information to fill in. So when the user clicks on a link to load a module the loadSection(); function is called. This is what the loadSection(); function looks like:
function loadSection(id, div, size, frame) {
var url = "loadSection.php?id=" + id + "&size=" + size + "$frame=" + frame;
$.get(url,
function(data){
$(div).append(data);
});
}
If I put the `$(#mainForm).validate();' in the callback of this function, it has the potential to get called every time a new module is inserted. Which may be good, or may be bad, I'm not sure how the validation will take to be called multiple times on the same form, even if the fields of the form have changed.
Thoughts?
You've likely got the problem right. If the form doesn't exist in the DOM at document.ready(), then nothing will be bound.
Since you're using JQuery, I presume the form is added using the jquery $.ajax (or similar) function. The most straightforward solution would be just to add $("#mainForm").validate(); to the callback function of the AJAX request. If you're not using JQUery ajax, please post the code that's adding the form, and we can help you out further.
you have to specify the class definition to element as required for it to validate that particular element in the form. But I guess you are not having it anywhere so its showing like that.
for example if you want to validate the email:
<p>
<label for="cemail">E-Mail</label>
<em>*</em><input id="cemail" name="email" size="25" class="required email" />
</p>
Simple mistake in selector "mainform" is not a valid selector. Add "#" prefix if it is an ID
EDIT: Also notice you have another validate call inline , remove that one
I am trying to use the jQuery POST function but it is handling the request in AJAX style. I mean it's not actually going to the page I am telling it to go.
$("#see_comments").click(function() {
$.post(
"comments.php",
{aid: imgnum},
function (data) {
}
);
});
This function should go to comments.php page with the aid value in hand. It's posting fine but not redirecting to comments.php.
#Doug Neiner Clarification:
I have 15 links (images). I click on a link and it loads my JavaScript. The script knows what imgnum I opened. This imgnum I want in the comments.php. I have to use this JavaScript and no other means can do the trick. The JavaScript is mandatory
Your method successfully POSTs the aid value. But in the comments.php when I try to echo that value, it displays nothing.
I am using Firebug. In the Console, it shows the echo REQUEST I made in Step (2) successfully.
I know what you are trying to do, but its not what you want.
First, unless you are changing data on the server, don't use a POST request. Just have #see_comments be a normal <a href='/comments.php?aid=1'>...
If you have to use POST, then do this to get the page to follow your call:
$("#see_comments").click(function() {
$('<form action="comments.php" method="POST">' +
'<input type="hidden" name="aid" value="' + imgnum + '">' +
'</form>').submit();
});
How this would actually work.
First $.post is only an AJAX method and cannot be used to do a traditional form submit like you are describing. So, to be able to post a value and navigate to the new page, we need to simulate a form post.
So the flow is as follows:
You click on the image, and your JS code gets the imgnum
Next, someone clicks on #see_comments
We create a temporary form with the imgnum value in it as a hidden field
We submit that form, which posts the value and loads the comments.php page
Your comments.php page will have access to the posted variable (i.e. in PHP it would be $_POST['aid'])
$("#see_comments").click(function () {
$('<form action="comments.php" method="POST"/>')
.append($('<input type="hidden" name="aid">').val(imgnum))
.appendTo($(document.body)) //it has to be added somewhere into the <body>
.submit();
});
While the solution by Doug Neiner is not only correct but also the most comprehensively explained one, it has one big problem: it seems to only work at Chrome.
I fidgeted around for a while trying to determine a workaround, and then stumbled upon the second answer by devside. The only difference is the extra code appendTo($(document.body)). Then I tested it in firefox and it worked like a charm. Apparently, Firefox and IE need to have the temporary form attached somewhere in the DOM Body.
I had to do this implementation for a Symfony2 project, since the path generator inside the .twig templates would only work with GET parameters and messing with the query string was breaking havoc with the security of the app. (BTW, if anyone knows a way to get .twig templates to call pages with POST parameters, please let me know in the comments).
i think what you're asking is to get to 'comments.php' and posting aid with value imgnum. The only way to do this is to submit this value with a form.
However, you can make this form hidden, and submit it on an arbitrary click somewhere with jquery.
html necessary (put anywhere on page):
<form id='see_comments_form' action='comments.php' action='POST'>
<input id='see_comments_aid' type='hidden' name='aid' value=''>
</form>
js necessary:
$("#see_comments").click(function(){
$('#see_comments_aid').val(imgnum);
$('#see_comments_form').submit();
);
this will redirect to 'comments.php' and send the proper value imgnum (that i assume you are getting from somewhere else).
Actually, $.post() sends some data to the server. It does not cause any redirection unless you do it in your server side code which handles the POST request. I can suggest two solutions:
To go to comment page, instead of using JQuery post, you can simply use a 'anchor' tag - Show Comments.
Or if you are want to go through JQuery, you can use this code snippet: $(location).attr("href", "comments.php?aid=1");
didnt exactly solve the problem. but did manage to work around it. i had to do a lot modification to the JS to make this work, but the core problem of this question was solved by doing this:
$("#see_comments").attr({href: "comments.php?aid='"+imgnum+"'"});
this appended the aid value to the URL as #Doug Neiner initially suggested me to do.
Thanks a lot Doug for all the effort. I really appreciate. +1 and accept to your answer for the effort.