PHP / JS: repeating multiple variables without losing their value

The JS / Ajax function that I created is dispatched without a button click or page refresh. The function receives the values โ€‹โ€‹of the input field and with the help of php displays the results. But each time the variable echoes, the next variable erases the value of the previous one. How can this be avoided? EXAMPLE

Js

<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_name').on('keyup', function() { clearTimeout(timer); timer = setTimeout(submitForm, 050); var name = $("#contact_name").val(); dataString = 'name='+ name; }); $('#email').on('keyup', function() { clearTimeout(timer); timer = setTimeout(submitForm, 050); var name = $("#email").val(); dataString = 'name='+ name; }); $('#phone').on('keyup', function() { clearTimeout(timer); timer = setTimeout(submitForm, 050); var name = $("#phone").val(); dataString = 'name='+ name; }); $('#address').on('keyup', function() { clearTimeout(timer); timer = setTimeout(submitForm, 050); var name = $("#address").val(); dataString = 'name='+ name; }); $('#website').on('keyup', function() { clearTimeout(timer); timer = setTimeout(submitForm, 050); var name = $("#website").val(); dataString = 'name='+ name; }); }); </script> 

HTML / PHP

 <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 $contact_name ?>" /> <div id="special"><span id="resultval"></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 $email ?>" /> <div id="special"><span id="resultval"></span></div> </div><!-- end .input--> </div><!-- end .row --> </form> 
+4
source share
2 answers

you can use the append() method:

 success: function(result){ $('#special').append('<p>' + result + '</p>'); } 

since you set up similar classes for inputs that you can minimize code:

  $('.detail').on('keyup', function() { clearTimeout(timer); var name = $(this).val(); dataString = 'name='+ name; timer = setTimeout(submitForm, 050); }); 

note that the identifiers must be unique, and re-requesting data from the server is inefficient.

+4
source

You are having trouble using the same identifiers for multiple items.

Identifiers must be unique, but in case of identical identifiers, only the first element with such an identifier is selected.

+1
source

All Articles