TheGreenDAS TheGreenDAS -4 years ago 71
Ajax Question

AJAX jQuery Iterate through response on Button Click

I am new to Coding and I got stuck for hours solving this problem:

The response from AJAX is a Json two-dimesional array

the first index
describes each product id, the second one holds product details like prices etc.
So all i want to is to iterate through the first index by using the button "New_Suggestion" and to update the html content in the "result_wrapper".

The response works fine, but updating the html content doesn't work at all.

Thank you for your help.

type: "POST",
url: "productsuggestion.php",
data: "criteria1=" + crit1 + "&criteria2=" + crit2 + "&criteria3=" + crit3 + "&criteria4=" + crit4 + "&criteria5=" + crit5,
dataType: "json",
success: function(jqXHR) {

var sug = 0;

$('#New_Suggestion').on('click', function() {

sug = sug + 1


'<div id="prod_name">' + jqXHR[sug][0] + '</div> <br>' +
'<img id="prod_pic" src="' + jqXHR[sug][4] + '">' +
'<div id="prod_price">' + jqXHR[sug][2] + '</div> <br>'


Answer Source

Firstly, your "click" handler just increments a variable when it's clicked. It doesn't touch the output at all.

Secondly, every time the ajax runs, you add another click event handler to the button, without removing the previous one(s). It's easier to declare this outside the ajax context, and set a global variable for the suggestion count.

Something like this, I think (untested):

var sugCount = 0;
var sugData = null;

  type : "POST",
  url  : "productsuggestion.php",
  data : "criteria1="+crit1+"&criteria2="+crit2+"&criteria3="+crit3+"&criteria4="+crit4+"&criteria5="+crit5,
  dataType: "json",
  success: function(data){
    //reset global data after each ajax call
    sugCount = 0; 
    suggestionData = data;
    writeSuggestions(sugCount, sugData); //output the initial set of suggestions

  sugCount = sugCount + 1;
  writeSuggestions(sugCount, sugData); //output updated suggestions

function writeSuggestions(count, data)
  $("#result_wrapper").html('<div id="prod_name">'+data[count][0]+'</div> <br>'+
                    '<img id="prod_pic" src="'+data[count][4]+'">'+
                    '<div id="prod_price">'+data[count][2]+'</div> <br>');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download