I am new to programming and I am playing around with htm/ajax/php. I have two text fields, name and animal. You input a name into the name field. If the name exists in the database it returns all the animals associated with that name and does not allow a duplicate animal to be entered into the animal field. I am doing the validation with LiveValidation.
So far I have the name field working fine. It is checking the database and returning a coma separated list of all the animals associated with that name, and inserting them into the results div. However the results div is just for testing. What I want is for the results list to populate the list here:
//animal must not include
var animal = new LiveValidation('animal');
animal.add(Validate.Exclusion, {
within: [
// Insert ajax results here
'cow' , 'pigeon', 'giraffe',
]
} );
Here is the rest of my code. I think what I am trying to do is fairly simple I am just not sure how to go about doing it. Thanks to anyone who takes some time to help me out.
HTML
<input type="text" id="name" name="name"/>
<input type="text" id="animal" name="animal" />
<div class="results"></div>
JavaScript
<script>
//ajax call
$(function(){
$('#name').blur(function(){
var inpval = $('#name').val();
$.ajax({
type: 'POST',
data: ({name : inpval}),
url: 'name_taken.php',
success: function(data) {
$('.results').html(data);
}
});
});
});
//validation from livevalidation.com
//name must be present
var name = new LiveValidation('name');
name.add(Validate.Presence);
//animal must not include
var animal = new LiveValidation('animal');
animal.add(Validate.Exclusion, {
within: [
// How do I insert ajax results here?
'cow' , 'pigeon', 'giraffe',
]
} );
</script>
PHP
//name_taken.php
$input_name = trim($_POST['name']);
foreach($names_table as $row){
$name = $row['name'];
if($name == $input_name){
echo $row['animal'] . ',';
}
}
Table Structure
//$names_table
| 1 | Dave | animal1 |
| 2 | Mark | animal2 |
| 3 | Dave | animal3 |
with your ajax function you can use dataType
to set the return data type
//animal must not include
var animal = new LiveValidation('animal');
var obj = {
within: [
'cow' , 'pigeon', 'giraffe',
]
};
animal.add(Validate.Exclusion, obj);
$.ajax({
type: 'POST',
data: ({name : inpval}),
dataType: 'json',
url: 'name_taken.php',
success: function(data) {
obj.within = new Array();
for(var i in data){
obj.within.push(data[i]);
}
animal.add(Validate.Exclusion, obj);
}
});
then in your php you just need to use json_encode()
like this:
<?php
$array = array(1,2,3,4,5,6);
echo json_encode($array);