JsFiddle testing jQuery AJAX request with echo

The following code warns of 'undefined' and does not add 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>​ 

JsFiddle example: http://jsfiddle.net/L6bJ2/3/

+4
source share
2 answers
  • The HTTP method is set using type , not method , so you should use;

     type: 'post', 
  • Since you specified the response type as HTML, you get the string passed in the data parameter of the success callback; but it looks like you are expecting JSON when 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 will find it works: http://jsfiddle.net/L6bJ2/6/

+9
source

A live example is here fooobar.com/questions/19174 / ...

use before sending or perform callback functions when calling ajax,

Source ShoutingCode

0
source

Source: https://habr.com/ru/post/1401349/


All Articles