Reputation: 123
I have te following script and want to pass a value to a textbox using AJAX.
<script>
$(document).ready(function(){
$("#searchName").change(function(){
var name = $("#searchName").val();
$.ajax({
'url': 'ontwikkelpunten.php',
'method': 'post',
'data':
{
naam: $("#searchName").val()
},
'dataType': 'json'
}).done(function(data){
console.log(data);
$('#test').val(data.naam);
});
});
});
<input type="text" id="test" name="">
When I change searchName and check the console in Chrome I see the array, but its still not working.
Upvotes: 1
Views: 293
Reputation: 4104
Your JSON return is an array of objects (in your case, a single array element containing an object). So when you tried to assign with:
$('#test').val( data.naam );
// ^--- direct object item reference
This was not finding the right element to use because naam
didn't exist in the base array. Instead you need to adjust that to first reference the array element, THEN the object element:
$('#test').val( data[0].naam );
// ^--- first array element
Upvotes: 1