I have a GUI with various fields in which user can enter data.
I have a button.
I want to pass values entered by user on the GUI, and on the button click, I want to pass those values to another page where i can use them.
Note: No form/No onSubmit/No form action, it is just a page redirect to another page using a button.
Based on some markup:
<div id="x">Some data</div>
<div id="y">Some more data</div>
jQuery script to retrieve the data you want:
$("my button/link/whatever").click(function(e) {
e.preventDefault();
var data = {
x: $("#x").text(),
y: $("#y").text()
};
var req = $.ajax({
url: "the page to send data to",
type: "post",
data: data
});
req.done(function(response) {
// Do something here once the request is complete
});
});
Or use a second form.
Related
I thought the HTML spec stated that buttons click in a form pass their value, and button "not clicked" did not get passed. Like check boxes... I always check for the button value and sometimes I'll do different processing depending on which button was used to submit..
I have started using AJAX (specifically jquery) to submit my form data - but the button data is NEVER passed - is there something I'm missing? is there soemthing I can do to pass that data?
simple code might look like this
<form id="frmPost" method="post" action="page.php" class="bbForm" >
<input type="text" name="heading" id="heading" />
<input type="submit" name="btnA" value="Process It!" />
<input type="submit" name="btnB" value="Re-rout it somewhere Else!" />
</form>
<script>
$( function() { //once the doc has loaded
//handle the forms
$( '.bbForm' ).live( 'submit', function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $( this ).serialize(), // get the form data
type: $( this ).attr( 'method' ), // GET or POST
url: $( this ).attr( 'action' ), // the file to call
success: function( response ) { // on success..
$('#ui-tabs-1').html( response );
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
On the processing page - ONLY the "heading" field appears, neither the btnA or btnB regardless of whichever is clicked...
if it can't be 'fixed' can someone explain why the Ajax call doesn't follow "standard" form behavior?
thx
I found this to be an interesting issue so I figured I would do a bit of digging into the jquery source code and api documentation.
My findings:
Your issue has nothing to do with an ajax call and everything to do with the $.serialize() function. It simply is not coded to return <input type="submit"> or even <button type="submit"> I tried both. There is a regex expression that is run against the set of elements in the form to be serialized and it arbitrarily excludes the submit button unfortunately.
jQuery source code (I modified for debugging purposes but everything is still semantically intact):
serialize: function() {
var data = jQuery.param( this.serializeArray() );
return data;
},
serializeArray: function() {
var elementMap = this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
});
var filtered = elementMap.filter(function(){
var regexTest1= rselectTextarea.test( this.nodeName );
var regexTest2 = rinput.test( this.type ); //input submit will fail here thus never serialized as part of the form
var output = this.name && !this.disabled &&
( this.checked || regexTest2|| regexTest2);
return output;
});
var output = filtered.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
return output;
}
Now examining the jQuery documentation, you meet all the requirements for it to behave as expected (http://api.jquery.com/serialize/):
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. For a form element's value to be included in the serialized string, the element must have a name attribute. Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked. Data from file select elements is not serialized.
the "successful controls link branches out to the W3 spec and you definitely nailed the expected behavior on the spec.
Short lame answer: I think it is teh broken! Report for bug fix!!!
I've run into a rather unusual issue with this. I'm working on a project and have two separate php pages where one has html on the page separate from the php code and one is echoing html from inside php code. When I use the .serialize on the one that has the separate html code it works correctly. It sends my submit button value in its ajax call to another php page. But in the one with the html echoed from the php script I try to do the same thing and get completely different results. It will send all of the other info in the form but not the value of the submit button. All I need it to do is send whether or not I pushed "Delete" or "Update". I'm not asking for help (violating the rules of asking for help on another persons post) but I thought this info might be helpful in figuring out where the break down is occurring. I'll be looking for a solution and will post back here if I figure anything out.
I'm new to Dojo and have a problem with my onChange() event, it runs when the page loads and not when the value in the Select box is changed. Here's my code, its all in the body section section of the page. Thanks for your help.
<div id="supportCentersListBox" data-dojo-type="dijit.form.Select"></div>
<script type="text/javascript">
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.form.Select");
function populateSupportCenters() {
var supportCenters = new dijit.form.Select({
maxHeight:"300",
id: "supportCenters",
onChange: changeTest(),
store: new dojo.data.ItemFileReadStore( { url: "some url address here" })
}, 'supportCentersListBox');
}
function changeTest() {
alert("Changed");
}
populateSupportCenters();
</script>
Fix your code so that the onChange is not a function call but instead a function pointer/reference
You have this 'problem':
<div id="supportCentersListBox" data-dojo-type="dijit.form.Select"> DOM renders (data-dojo-type is for parseOnLoad (dojo.parser) only, dont need it since youre creating it yourself
you instantiate a store
you instantiate a Select and render in supportCentersListBox - with store set, that fetches the url
fetch completes and Select is filled in
the item which has attribute selected:true or the first in index is set as value
onChange fires
I'm investigating the suitability of the jQM history management for my organization's mobile web site. Part of our requirement is that when a user posts a form, it posts using Ajax. When a user taps "back" and then "forward" browser buttons, we need to re-post the form using Ajax again. Here's a diagram:
[home.php: post to new.php] =>
[new.php: post to list.php] =>
[from list.php, click back twice to home.php] =>
[* home.php: click fwd, does a GET request to new.php *] =>
[* new.php: click fwd, does a GET request to list.php *]
[*] not the behavior I want. I want to re-POST data from steps 1 and 2
During steps 4 and 5, I want to intercept the jQM execution at the "pagebeforeload" event (seems like the right place), and modify the data.options.data (to include the serialized post data) and data.options.type (to POST) properties of the data object which is passed to the event handler. Then I'd let the pageload process move on with the modified values. This, I think, would give me the behavior I want.
So far, I see that I can intercept the pagebeforeload event and modify the values with the below event handler:
$(document).bind("pagebeforeload",
function( e, data ) {
console.log(data.toPage);
console.log(data.options);
data.options.type = "POST";
data.options.data = "edit=Hanford";
}
);
But the missing piece is, how can I "store" the information in steps 1 and 2, such that when I intercept the pagebeforeload event in 4 and 5, I can know to modify the "type" and "data" properties properly.
I've made a jquery/browser History prototype to illustrate the behavior I would like to get from jQuery Mobile. The JavaScript is:
$(window).load(function() {
//listen to the history popstate event
$(window).bind('popstate',
function(e) {
if (e.originalEvent.state && e.originalEvent.state.type && e.originalEvent.state.type == "post") {
//do an ajax post based on what is stored in history state
$.post(e.originalEvent.state.path,
e.originalEvent.state.data,
function(data) {jaxer(data,'POST')});
} else if (e.originalEvent.state !== undefined){
//do an ajax get
$.get(location.pathname,
function(data) {jaxer(data,'GET')});
}
});
//add event listeners
addClickHandler();
});
function jaxer(data, msg) {
if (msg) {console.log(msg+' request made using ajax');}
$('#slider')[0].innerHTML = data;
addClickHandler();
}
//hijax hyperlinks and form submissions
function addClickHandler() {
$('a').click(function(e) {
history.pushState({
path: this.path
},
'', this.href);
$.get(this.href,
function(data) {jaxer(data,'GET')});
e.preventDefault()
});
$('form').submit(function(e) {
var formData = $(this).serialize();
console.log('saving serialized form data into historyState: '+formData);
history.pushState({path: this.action, data: formData, type: "post"},'',this.action);
$.post(this.action,
$(this).serialize(),
function(data) {jaxer(data,'POST')});
e.preventDefault();
});
//add the form submit button to the form as a hidden input such that it will get serialized
$('form input[type="submit"]').click(function() {
$(this.form).append("<input type='hidden' name='" + this.name + "' value='" + this.value + "'/>");
});
console.log("event handlers added to DOM");
};
When a user-initiated POST occurs, I put the serialized POST data into the history's state object. Then, when a popstate event occurs, I can query the state object for this information. If I find it, then I can perform an ajax POST. I would like to get the same functionality within the jQuery Mobile history handling. That way I can take advantage of the page change animations, etc.
I m having a page with two date fields and a dropdown... based on the values selected from those fields i have to call a server method which fetches the data and then bind the grid.. how is this possible using jquery grid... currently i know that i can call $("#list").jqGrid({}); on a button click which is inside a function... but the problem is that i want to pass additional parameters also...
$(function() {
$('#someButton').click(function() {
// when the button is clicked
// send an AJAX call to the server to fetch data:
$.ajax({
url: '/home/someaction',
data: {
// Use the data hash to send values to the server action
date1: $('#date1').val(),
date2: $('#date2').val(),
ddlValue: $('#ddl').val()
},
success: function(result) {
//TODO: setup jqGrid here based on the results
// returned from the server action
}
});
});
});
I have a popup (which I used by necessity) that is opened on a link click. I have the user going through a series of pages picking attributes to then be sent to a shopping cart.
My problem: After the user reaches the end of the selection process i want to kill the open popup and send the request back to the original browser (parent) so the user can checkout.
Any idea how I would do this?
Javascript: in the child (popup) window.
window.opener.location = 'page.html";
window.close();
Is that what your looking for?
The parent window can be accessed using "opener" in JavaScript.
Example:
window.opener.title='hello parent window';
or
window.opener.location.href='http://redirect.address';
Script in my child form:
<script language="JavaScript" type="text/javascript">
function SetData() {
// form validation
// var frmvalidator = new Validator("myForm");
// frmvalidator.addValidation("name","req","Please enter Account Name");
// get the new dialog values
var str1 = document.getElementById("name").value;
var winArgs = str1;
// pass the values back as arguments
window.returnValue = winArgs;
window.close();
document.myForm.submit();
}
</script>
Script in my parent form:
<% #account_head= current_company.account_heads.find_by_name("Sundry Debtors")%>
<script type="text/javascript">
function OpenDialog() {
var winSettings = 'center:yes;resizable:no;help:yes;status:no;dialogWidth:450px;dialogHeight:200px';
// return the dialog control values after passing them as a parameter
winArgs = window.showModalDialog('<%= "/accounts/new?account_head_id=#{#account_head.id} #man" %>', winSettings);
if(winArgs == null) {
window.alert("no data returned!");
} else {
// set the values from what's returned
document.getElementById("to_account_auto_complete").value = winArgs;
}
}
</script>
This is work but not as i want, any one if found good solution please suggest.