Reputation: 59168
I want to submit a form without page refresh using jQuery. I found some examples online, like this one: http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
but the problem is they have hard-coded form fields:
<div id="contact_form">
<form name="contact" action="">
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label>
<label for="email" id="email_label">Return Email</label>
<input type="text" name="email" id="email" size="30" value="" class="text-input" />
<label class="error" for="email" id="email_error">This field is required.</label>
<label for="phone" id="phone_label">Return Phone</label>
<input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
<label class="error" for="phone" id="phone_error">This field is required.</label>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
</div>
And the javascript:
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "bin/process.php",
data: dataString,
success: function() {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("<h2>Contact Form Submitted!</h2>")
.append("<p>We will be in touch soon.</p>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='checkmark' src='images/check.png' />");
});
}
});
return false;
So in the example above, the dataString
is created from hard-coded form fields. My form is dynamic so I don't know the name of input fields it has.
Note: Although the form fields are dynamic, the form name is hard-coded, so I guess one option is to go through child nodes and parse the values. But I was wondering if there is an easier way.
Upvotes: 1
Views: 8005
Reputation: 4983
Caner, I fear since your form is dynamic there isn't an easier way. You need to go through your form using code like such:
var message = "";
$("#formID input").each(function() {
message += $(this).attr("name");
});
Such a code will get the name of each input in the form and concatenate it to a string called message. You can be more specific than I was in this case, but you should get the basic idea and use this code to fit it to your needs.
Upvotes: 1