Solved

jquery AJAX generated form variable not sent

Posted on 2011-02-20
13
1,296 Views
Last Modified: 2012-05-11
I have a form that I submit using jQuery AJAX (see snippet). It works fine, and the result shows in the appropriate div when a submit button is clicked. The result appears as an extension of that form, with a group of radio buttons, and a second submit button. The closing form tag is after the second submit button. The second submit button has a different name and ID.

In the jQuery code, I have defined the variable for the radio buttons, and added a hidden element, to flag which button was clicked. I defined the hidden elements variable.

But when I click on the second submit button, all the original data in the non-AJAX generated form is sent back to the processing php program, but the variable in the AJAX generated code are not.

Am I asking too much? Do I need to create a second form within the AJAX code?

Also, to get the value of the radio buttons, I am using var roundtrip=$("#dividcontainer input:radio:checked").val();  where dividcontainer is the id of a div that surrounds the first set of radio buttons. But if I enter the identical code, just changing the variable name and the id name, for the second set of radio buttons (the one on the AJAX generted code) the jQuery code fails when I add the variable name to the data list. ( +"newVehicle="+newVehicle.val() ).

I'd appreciate any guidance that I can get.
<script type="text/javascript">
$(function(){
	var vehicle = $("#vehicle");
	var pickup = $("#PICKUP");
	var dropoff = $("#DROPOFF");
	var error = $("#error");
	var postwrap = $("#postwrap");
	var roundtrip = $("#roundtrip");
	var passengers = $("#passengers");
	var bookit = $("#bookit");
	var newVehicle = $("#newVehicle");
	$("#vsearch").submit(function(){
		if((pickup.val() == "" || pickup.val()=="Choose Your Pickup Location") || (dropoff.val() == "" || dropoff.val()=="Choose Your Destination" || vehicle.val()=="")){
			error.text("You must select a pickup location, a destination, and a vehicle").fadeIn(900).delay(2000).fadeOut(900);
			return false;
			}   	
		else{
			var roundtrip=$("#dividcontainer input:radio:checked").val();
var newVehicle=$("#divRateContainer input:radio:checked").val();
			$.ajax({
				type: "POST",
				url: "AJAX_process_rates.php",
				data: "vehicle="+vehicle.val()+"&pickup="+pickup.val()+"&dropoff="+dropoff.val()+"&passengers="+passengers.val()+"&roundtrip="+roundtrip+"&bookit="+bookit.val()+"&add=true",
							success: 
							function(r){
							postwrap.html(r);
							postwrap.hide().show(1000);$("#success").text("Post added").fadeIn(300).delay(900).fadeOut(300);
}, 
				error: function(){$("#error").text("Could not add post").fadeIn(300).delay(900).fadeOut(300)}
			});
			return false;
			}
	}
)});
	</script>

Open in new window

0
Comment
Question by:birwin
  • 7
  • 4
  • 2
13 Comments
 
LVL 40

Expert Comment

by:RQuadling
ID: 34947720
Are the newly added inputs set as child elements to the form element?

<form><input /><input /></form>

or

<form><input /></form><input />

The new input tags must be within the form tag.

Or you have to multiple form tags and attach the submit handler to each newly created form.

Do you have a live link?
0
 
LVL 6

Author Comment

by:birwin
ID: 34947906
The structure is like this:

<form><input><select><input>. . . <submit name="name1"> <div for AJAX results><*radio><*checkbox> <*hidden> </div end of AJAX> <submit name="name2"> </form>

* indicates inserted from server by jQuery AJAX call

It is a client site, so I can't publicly post it, but I'll email it to you, using the email address in your profile.

I appreciate your help with this.

Brian
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 34948044
As I expected, the elements you've added, which include

<input type="hidden" name="bookit" id="bookit" value="bookit">

are outside of the form tag, so are not going to be submitted with the form.

You need to alter the initial HTML to allow for the trip data to be part of the form.

So, maybe the following would work.

1 - Move the <form> tag out of the <table>. Put the <table> inside the <form> tag.
2 - Add a <tfoot> to the <table>
3 - Put the trip data into the <tfoot>

Now, when you click the book this trip button, it will have all the data in the form ready to go.
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 34948063
And you're HTML isn't balanced.

Tags have to be nested ...

<tag1><tag2>data</tag2></tag1>

It looks like you have ...


<tag1><tag2>data</tag1></tag2>

What the browser will then do is ...


<tag1><tag2>data</tag2 inserted></tag1></tag2 probably ignored>

You can see the difference if you use a modern browser (I use Google Chrome) and look at the difference between the view-source and the DOM view. In Chrome view-source and inspect element.

0
 
LVL 40

Expert Comment

by:RQuadling
ID: 34948076
Having done more reading of your code, it seems that ...

<span id='ajax-message'></span></form>

is in completely the wrong place.

Putting the span in the tfooter and putting </form> in the right place will help.

I'd STRONGLY recommend you put the HTML code through a HTML validator : http://validator.w3.org/check?uri=http%3A%2F%2Fwww.whistlertransport.com%2Findex2.php&charset=%28detect+automatically%29&doctype=Inline&group=0&ss=1&st=1&outline=1&No200=1&verbose=1

for example.
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 34948089
There are a lot of significant errors in the HTML code that will cause you all sorts of headaches trying to get things working.

A browser can only guess your intent so far. And they won't all guess the same way. If the HTML code doesn't obey the rules, each browser has its own way of thinking. The javascript then sits on top of what the browser decided you meant in the HTML. In this instance, there is a major difference between the HTML and the DOM. So, things like the AJAX'd in form elements are added outside of the form element and then fail to be picked up correctly.

When you start using tools like AJAX/jQuery/Prototype, it is expected that the DOM matches the HTML to an extremely high degree. Validating the HTML before even attempting to add an additional behaviour with javascript is essential.

Richard.
0
Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

 
LVL 6

Author Comment

by:birwin
ID: 34948632
Hi RQuadling:

Thank you for pointing me to the validator. I have updated the code, and it now passes the validator, wiith the exception of the img tags in the select tags for vehicle. That is a pseudo element that a jQuery module uses to allow me to show the image of the selected vehicle.

Unfortunately, non of the values from the AJAX generated code are being passed to the server side porgram that receives the form data. I know that it is possible to pass data from AJAX created form extensions, because I am doing it with some other programs, but for some reason, this code won't do it.

Any help you can give will be appreciated.

Brian

0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 34949237
Not only the code you have, but the code you generate needs to be well formed.

Use firebug or webdeveoper to see if the fields are properly attached to the form
0
 
LVL 40

Expert Comment

by:RQuadling
ID: 34949389
The form data that is being transmitted is ...

vehicle:2
pickup:Bosmans Hotel ~  Vancouver
dropoff:Carleton Lodge ~  Whistler
passengers:1
roundtrip:YES
newVehicle:2
bookit:undefined
submit:undefined
add:true


So, it looks like the fields _are_ now in the form, but you are not populating them with valid values.

When you run the javascript code you have ...


      var bookit = $("#bookit");
      var newVehicle = $("#newVehicle");


Can you put this line after wards ...

alert(bookit);

You should see undefined as an alert.

And you should only see it once. I think you are getting the value too early. You should only do this when the "book it" button is pressed, not during the get prices ajax call.
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 34949425
Could it possibly be that you are chopping off the url at some value too?

Perhaps you need to do
"&whatever="+escape(whatever.val())
0
 
LVL 6

Author Comment

by:birwin
ID: 34950100
Hi RQuadling:

I get [object Object] from the alert.

I am not sure what I did to make it happen, but I am now getting the value of the selected radio button from the variable newVehicle, but I am not getting any value for bookit or submit.

0
 
LVL 40

Accepted Solution

by:
RQuadling earned 500 total points
ID: 34963609
The alert happens too early. It is BEFORE I have chosen the values to send.

The reason you get an [object Object] is that the result of $("bookit") is an empty (ish) object.

It is NOT a link to the #bookit element as that element doesn't exist yet.

In trying to just get the code working for you, without rewriting it, ... can you move ...

      $("#vsearch").submit(function(){

to the top of the function that it is in?

In essence this is currently happening...

1 - Page loads.
2 - $(function(){
      var vehicle = $("#vehicle");
        ...
      var bookit = $("#bookit");
        ...
      alert(bookit);

is run upon page load, showing the alert.

At this time, the variable called bookit contains an empty array.

3 - ("#vsearch").submit(function(){.... assigns a handler to the form submission code.
4 - I fill the form in and press submit.
5 - An ajax call is made and some HTML is returned containing the bookit element and the DOM is updated.
6 - The function defined in step 3 above runs.
7 - It attempts to get the value within the variable bookit, which is undefined as it is an empty array.
8 - This is sent to the server and reported as undefined.

In fact, "bookit" doesn't occur anywhere in the HTML source except in the javascript related to attempting to the variable bookit and the selector #bookit.

Not until the "Show me the rates" button is pressed. At that stage, the bookit element is added to the form.

Manually running $('#bookit') at that stage shows the correct element.

$('#bookit').val() returns a value of 'bookit'.

0
 
LVL 6

Author Closing Comment

by:birwin
ID: 34964683
Brilliant! That worked. Thank you so much for all your help.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Any person in technology especially those working for big companies should at least know about the basics of web accessibility. Believe it or not there are even laws in place that require businesses to provide such means for the disabled and aging p…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now