Skip to content

How to output the response HTML data by a jQuery AJAX request?

In a jQuery AJAX request, you can output the response HTML data using the .html() method. For example, if you make an AJAX request to a URL and want to output the response HTML data to a div with the ID myDiv, you can use the following code:

Example of making an AJAX request to a URL and outputting the response HTML data to a div with the ID of myDiv

javascript
$.ajax({
  url: 'example.com',
  dataType: 'html',
  success: function(response) {
    $('#myDiv').html(response);
  }
});

You can also use the .text() method if you want to output the response as plain text instead of HTML.

Example of making an AJAX request to a URL and using the .text() method to output the response as plain text

javascript
$.ajax({
  url: 'example.com',
  dataType: 'html',
  success: function(response) {
    $('#myDiv').text(response);
  }
});

Note that the above examples use the shorthand $.ajax method with a success callback. You can also use the .done() method to handle the success callback. Check the jQuery documentation for more details on different ways to handle AJAX requests.

Dual-run preview — compare with live Symfony routes.