Jump to content

AJAX Content not showing up in form post


jhatton

Recommended Posts

Hello There,

I am new to the forum and AJAX and looking for a little help.  I have two select boxes one for states and one for counties.  When the state changes the county updates.  This works great.  However when I post the form to the server the selected county is not provided as part of the post.  When updating a page fynamically using .innerHTML method its almost as if the form is not aware something has been updated and therefore does not include it in the post. 

Here is my AJAX which is working fine.  Should I use something other then .innerHTML to get the form to recognize it has been updated?

many thanks in advance to anyone who can help.  I have been stuck on this for a while now. :(

[code]

var req;
  var which;

  function lookupState1Counties(url) {
     
    if (window.XMLHttpRequest) { // Non-IE browsers
      req = new XMLHttpRequest();
      req.onreadystatechange = loadState1Counties;
      try {
        req.open("GET", url, true);
      } catch (e) {
        alert(e);
      }
      req.send(null);
    } else if (window.ActiveXObject) { // IE
      req = new ActiveXObject("Microsoft.XMLHTTP");
      if (req) {
        req.onreadystatechange = loadState1Counties;
        req.open("GET", url, true);
        req.send();
      }
    }
  }

  function loadState1Counties() {
   
    if (req.readyState == 4) { // Complete
      if (req.status == 200) { // OK response       
        document.getElementById('County1').innerHTML = req.responseText;
      } else {
        alert("Problem: " + req.statusText);
      }
    }
  }

[/code]
Link to comment
Share on other sites

Unfortunately there is no live version.  I notice when I view the source after the ajax call the county drop down select box does not appear. Although it does appear on the page itself.  I guess this should be excepted as the source represents the way the page looked when it was initially rendered.

If you update a form element using AJAX can you still post the form using a regular submit or do you have to submit using XMLHTTPRequest also to get it to reconize the new form elements?
Link to comment
Share on other sites

The source of an AJAX-filled portion of the page will never be visible unless you use FF and the "view selection source" option.

You can submit using the regular submit... the JS should be able to read whatever is on the page no matter when it was put there.
Link to comment
Share on other sites

Ober,

Thank you very much for reminding me of the alternate view source option in Firefox.  My bug was that I have multiple select boxes named the same thing which caused every one except the first one to be omited from the form post. I assumed the innerHTML was to blame - many thanks also for confirming that this is not the case!  ;D

I do have another question.  Do you have an example of how I can actually submit a form using XMLHTTPRequest as a POST.  The example I have conducts the post but you have to manually tell it which form items to include - I would like to be able to add all form elements to the XMLHTTPRequest post without explicity specifing each item.

Here is the static version I want to make dynamic:

[code]
req2.open("POST", "ordersubmission.do", true);
req2.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req2.send("state=" + document.getElementById("stateid").value);
[/code]
Link to comment
Share on other sites

The only way to do that would be to use a script that runs through all the elements on the form and grabs their value, building an array of the inputs.  I don't have an example of that code because I normally just do it manually.  One thing I would recommend however, is breaking that out a little bit (create variables before the actual sending piece and then just stick those variables in the actual send.

That helps with 2 things.  If you ever need to debug it, you can just alert() the variable.  Secondly, it makes the actual send process a little more readable.

Something like this may help with getting all the elements:
[code]function dostuff() {
    if (!document.getElementsByTagName){ return; }
    var allfields = document.getElementsByTagName("input");

    // loop through all input tags and add events
    for (var i=0; i<allfields.length; i++){
        var field = allfields[i];
        if ((field.getAttribute("type") == "text") || (field.getAttribute("type") == "password") ) {
            // stuff
        }
    }
}[/code]

You can either modify that or probably find something else similar to do the work if you search the web for 5 minutes.
Link to comment
Share on other sites

Great!  I figured it could be done with some JS but was hoping their might be a utility method to handle this as I am sure it is a fairly common to have a form whose elements are dynamic.

You seem quite knowledgeable in this field - have you wroked with any of the ajax libararies such as Prototype or DoJo?  If so which do you recommend?

thanks,

James.
Link to comment
Share on other sites

Thanks... and no, I haven't worked with them.  I write my own from scratch.  I think most of those libraries are bloated and overwhelming and don't always do exactly what you want anyways.

And if there is a JS utitilty to grab all dynamic fields, I'm unaware of it.
Link to comment
Share on other sites

  • 1 month later...
I ran into a minor problem while writing a function that does just that.  The function is called [i]ajaxPrepareQS[/i] and takes as its parameter a list of form elements to build the query string out of.

My Javascript knowledge and experience is limited, so I'm open to critique on my code, but here it is:
[code]
// ajaxPrepareQS
// fields - array of form fields to encode for the AJAX request
// RETURN: the data string to pass to the server
function ajaxPrepareQS(fields){
  var escapeFunc = escape; // Set a function pointer in case we change
                          // later
  var passData = '';
  for(x in fields){
    if(fields[x].type == 'button' ||
      fields[x].type == undefined){
      continue;
    }
    var val = null;
    switch(fields[x].type){
      case 'text':
      case 'textarea':
      case 'password':
      case 'hidden':
        val = fields[x].value;
        break;
      case 'checkbox':
      case 'radio':
        if(fields[x].checked){
          val = fields[x].value;
        }
        break;
      case 'select-one':
        val = fields[x].options[fields[x].selectedIndex].value;
        break;
      case 'select-multiple':
        // This is a special case where we must set the passData
        // up here for each selected item in the list
        for(i in fields[x].options){
          if(fields[x].options[i].selected){
            if(passData.length != 0){
              passData += '&';
            }
            passData += fields[x].name + '='
                      + escapeFunc(fields[x].options[i].value);
          }
        }
        break;
    }
    // append the value to the full query string
    if(val != null){
      if(passData.length != 0){
        passData += '&';
      }
      passData += fields[x].name + '=' + escapeFunc(val);
    }
  }
  return passData;
}
[/code]

I used the following code to call it on all elements of my form:
[code]
  var e = document.optbid.elements;
  var fields = new Array;
  var i = 0;
  for(x in e){
    fields[i++] = e[x];
  }
  var qs = ajaxPrepareQS(fields);
[/code]

although I guess this would work just as well:
[code]
  var qs = ajaxPrepareQS(document.form_name.elements);
[/code]

When I make my AJAX calls, if the method is GET I append the returned value from [i]ajaxPrepareQS[/i] to the URL with a '?' in between them.  When I use POST I send the returned value in my xmlHttp.send().

Hope this helps.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.