jquery AJAX generated form variable not sent

Posted on 2011-02-20
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">
	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");
		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;
			var roundtrip=$("#dividcontainer input:radio:checked").val();
var newVehicle=$("#divRateContainer input:radio:checked").val();
				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",
							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;

Open in new window

Question by:birwin
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 4
  • 2
LVL 40

Expert Comment

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

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


<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?

Author Comment

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.

LVL 40

Expert Comment

by:Richard Quadling
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.
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

LVL 40

Expert Comment

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

Tags have to be nested ...


It looks like you have ...


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.

LVL 40

Expert Comment

by:Richard Quadling
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 :

for example.
LVL 40

Expert Comment

by:Richard Quadling
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.


Author Comment

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.


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
LVL 40

Expert Comment

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

pickup:Bosmans Hotel ~  Vancouver
dropoff:Carleton Lodge ~  Whistler

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 ...


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.
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

Author Comment

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.

LVL 40

Accepted Solution

Richard Quadling 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 ...


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");

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'.


Author Closing Comment

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

Featured Post

Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
When it comes to security, close monitoring is a must. According to WhiteHat Security annual report, a substantial number of all web applications are vulnerable always. Monitis offers a new product - fully-featured Website security monitoring and pr…
This tutorial demonstrates how to identify and create boundary or building outlines in Google Maps. In this example, I outline the boundaries of an enclosed skatepark within a community park.  Login to your Google Account, then  Google for "Google M…
This video teaches users how to migrate an existing Wordpress website to a new domain.

630 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