chnet
chnet

Reputation: 2033

jquery submit select box

I have a form. It consists of text area and select box. I want to submit it to server side. The following is front-end code. The back-end code has only one sentence: "print_r ($_POST);". It prints out the data users filled and selected. The problem is I can see the data users filled But I cannot see the data in select box. For example, I want to see:

Array ( [name] => hello [email] => ***@hotmail.com [list] => NYC) 

But it only shows:

Array ( [name] => hello [email] => ***@hotmail.com)

That said, it cannot show the data in selected box.

<form name="contact", action="ajax.php" method="POST">
    <fieldset>
      <label for="name" id="name_label">Name</label>
      <input type="text" name="name" id="name" size="30" value="" class="text-input" />

      <label for="email" id="email_label">Email</label>
      <input type="text" name="email" id="email" size="30" value="" class="text-input" />

      <select id="list" >
      <option></option>
      <option value="NYC">NYC</option>
      <option value="USA">USA</option>
      </select>

    <input type="submit" id="submit" value="Send" />
    </fieldset>
  </form>

<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>
 $(function() {
    $('#submit').click(function() {
      // validate and process form here
    $('.error').hide();
      var name = $("input#name").val();
      var email = $("input#email").val();
      var list = $("select#list").val();

      var dataString = 'name='+ name + '&email=' + email + '&list=' + list;
      alert(dataString); 
      $.ajax({
       type: "POST",
       data: dataString,
       url : "ajax.php",
     });   
   });
  });

</script>

Upvotes: 1

Views: 1362

Answers (1)

alex
alex

Reputation: 490283

There doesn't appear to be any errors with your code, however, creating the list of params yourself is redundant.

You could simply serialise that form with $('form[name="contact"]').serialize().

However, if you are submitting this form in addition to the XHR, you need to give the select element a name attribute.

Also, if you intended to submit via XHR and normal submission, I would prevent the default event for submit and call submit() in the success of your XHR. Otherwise, the request may not finish.

Upvotes: 1

Related Questions