The following code is alerting ‘undefined’ and not appending the html from the response data as I expected. Does anyone know why?
JavaScript:
$(function() {
$('.document').on('click', '.ajax', function(e) {
e.preventDefault();
// ajax request
$.ajax({
async: true,
cache: false,
type: 'post',
url: '/echo/html/',
data: {
html: '<p>This is echoed the response in HTML format</p>',
delay: 1
},
dataType: 'html',
beforeSend: function() {
console.log('Fired prior to the request');
},
success: function(data) {
console.log('Fired when the request is successfull');
$('.document').append(data);
},
complete: function() {
console.log('Fired when the request is complete');
}
});
});
});
HTML:
<div class="document">
<a class="ajax" href="#">Fire an AJAX request</a>
</div>
Example jsFiddle: http://jsfiddle.net/L6bJ2/3/
The HTTP method is specified with by
typerather thanmethod, so you should be using;Because you’ve specified the response type as HTML, you get a String passed in the
dataparameter of thesuccesscallback; but it looks like you’re expecting JSON as you’re trying to usedata.html. Instead, usedatadirectly;With these changes, you’ll find it works: http://jsfiddle.net/L6bJ2/6/