Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have an online shop with a shopping cart. The cart, which is a <table>, refreshes its content after adding an article to the cart.

I use jQuery's AJAX method which receives HTML <td><tr> as a response from the called PHP script. Firebug's console shows the correct response from the call.

As you can see in my code, I want to add HTML to the table. I can't get it to work. Do I not understand the AJAX method? I want to add these <td><tr> to the shopping cart table.

JavaScript (Using jQuery 1.9.1)

$.ajax({
    url: 'php/addToShoppingCart.php',
    type: 'POST',
    dataType: 'html',
    data: content,

    complete: function(data) {  
        $('#shop section table tbody').append(data);
    },
});

Firebug console

enter image description here

like image 309
Tomkay Avatar asked Mar 26 '13 09:03

Tomkay


People also ask

How do I get ajax response in HTML?

To retrieve that page using jQuery's AJAX function, you would simply use some javascript similar to the following. $. ajax({ url: 'test. html', dataType: 'html' });

How do I return a response from ajax?

Hello @kartik, What you need to do is pass a callback function to the somefunction as a parameter. This function will be called when the process is done working (ie, onComplete): somefunction: function(callback){ var result = ""; myAjax = new Ajax.

How can I get specific data from ajax response?

You can't as it's asynchronous. If you want to do anything with it, you need to do it in a callback. How? Because it's asynchronous, javascript will fire off the ajax request, then immediately move on to execute the next bit of code, and will probably do so before the ajax response has been received.

What does ajax request return?

The $.ajax() function returns the XMLHttpRequest object that it creates. Normally jQuery handles the creation of this object internally, but a custom function for manufacturing one can be specified using the xhr option.


2 Answers

have tried it using .done()?

$.ajax({
  url: 'php/addToShoppingCart.php',
  type: 'POST',
  dataType: 'html',
  data: content,
}).done(function ( data ) {
  $('#shop section table tbody').append(data);
});
like image 74
Stefan Candan Avatar answered Oct 14 '22 22:10

Stefan Candan


You can use the success also

  $.ajax({
       url: 'php/addToShoppingCart.php',
       type: 'POST',
       dataType: 'html',
       data: content, 
       success : function(data) 
      {$('#shop section table tbody').append(data);}
      });
like image 40
Devesh Avatar answered Oct 14 '22 21:10

Devesh