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

87,791

Solution 1

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);
});

Solution 2

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);}
      });
Share:
87,791
Tomkay
Author by

Tomkay

My Band

Updated on July 12, 2022

Comments

  • Tomkay
    Tomkay almost 2 years

    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

  • Mahendra
    Mahendra over 11 years
    'pid' could be add of current item that users is adding to cart And would be send by post method to your php file. if no data to send keep braces empty.
  • Devesh
    Devesh over 11 years
    What happens if we get the error while fetching , will done will still called and if yes what you will get in the data.
  • Stefan Candan
    Stefan Candan over 11 years
    done will still be called, and you'll get the error message, if your not sure your script is going to return an error, I'd recommend using success instead, but without further knowledge of the code in addToShoppingCart.php, I assumed he knew that his data would be correct.
  • Devesh
    Devesh over 11 years
    Yup , i wanted to point out the same , because error handling is also important in ajax
  • Stefan Candan
    Stefan Candan over 11 years
    I still believe error handling should be done server sided, not client sided. Gotta let the server do all the handling and let the client just show the data. Although working with success allows you to use status codes, it's just personal preference, I guess.