I am currently using Ajax/JS to submit a form without a page refresh or button click. I have set a timer with keyup to trigger the function. I have tested it with one input field and works well but now that other input fields have been added I am getting no results echoed out by the PHP. I have checked with firefox bug tool and the results are being stored. I am not sure if this a JS or PHP issue.
How can I properly echo the value of input field after the user has stop typing? EXAMPLE
JS/AJAX
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "index.php",
data: dataString,
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');}
});
return false;
}
$('#contact_form').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 2000);
var name = $("#contact_name, #email, #phone, #address, #website").val();
dataString = 'name='+ name;
});
});
</script>
HTML/PHP Snippet
<form action="" method="post" enctype="multipart/form-data" id="contact_form" name="form4">
<div class="row">
<div class="label">Contact Name *</div> <!-- end .label -->
<div class="input">
<input type="text" id="contact_name" class="detail" name="contact_name" value="<?php echo isset($_POST['contact_name'])? $_POST['contact_name'] : ''; ?>" />
<div id="special"><span id="resultval"><? echo $_POST['contact_name']; ?></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
<div class="row">
<div class="label">Email Address *</div> <!-- end .label -->
<div class="input">
<input type="text" id="email" class="detail" name="email" value="<?php echo isset($_POST['email'])? $_POST['email'] : ''; ?>" />
<div id="special"><span id="resultval"><? echo $_POST['email']; ?></span></div>
</div><!-- end .input-->
</div><!-- end .row -->
Rather than trying to do a mass assignment, you’ll need to build up your data. E.g., you currently have:
That jquery should match on the first identifier it matches, most likely the element with id contact_name, and that will be the only value name has, where as you’re hoping to get several form fields of data.
In fact, you shouldn’t need to build up dataString at all, as your data will be submitted by post via the form.
Rewriting the JS:
In your index.php, you can then access the form values in the $_POST array, e.g. $_POST[‘contact_name’].