4

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/

FelipeAls
  • 21,711
  • 8
  • 54
  • 74
RyanP13
  • 7,413
  • 27
  • 96
  • 166
  • there is no alert in your code, but I'm thinking your "alert" is executed faster than you ajax request so when you are trying to alert the ajax results, there are non because the ajax hasn finished at this point. – mas-designs Mar 14 '12 at 11:06

2 Answers2

9
  1. The HTTP method is specified with by type rather than method, so you should be using;

    type: 'post',
    
  2. Because you've specified the response type as HTML, you get a String passed in the data parameter of the success callback; but it looks like you're expecting JSON as you're trying to use data.html. Instead, use data directly;

    success: function(data) {
        console.log('Fired when the request is successfull');
        $('.document').append(data);
    },
    

With these changes, you'll find it works: http://jsfiddle.net/L6bJ2/6/

Matt
  • 74,352
  • 26
  • 153
  • 180
0

Live Example is here https://stackoverflow.com/a/34940340/5361795

use beforeSend or complete callback functions in ajax call,

Source ShoutingCode

Community
  • 1
  • 1
Zigri2612
  • 2,279
  • 21
  • 33