Jijo Nair
Jijo Nair

Reputation: 838

How to add element in XMLHttpRequest echoed from PHP?

at my controller side I have three data being echoed..

 echo $variant->Field1;

and at my client side , I have the below ajax code,

function variants(master_id,sku)
{

                  if(master_id=="")
                  {
                     document.getElementById("variants").innerHTML = "";     
                      return false;
                  }
                  else
                  {
                    var xhttp = new XMLHttpRequest();
                    xhttp.onreadystatechange = function() 
                      {
                        if (xhttp.readyState == 4 && xhttp.status == 200) 
                        {
                            document.getElementById("variants").innerHTML = xhttp.responseText;
                        }

                    };
                        xhttp.open("GET", "{{ url('/getVariants') }}"+'/'+master_id+'/'+sku, true);
                        xhttp.send();
                  }

Now I have `

 <div class="column">
          <div class="ui fluid image">
          <div class="ui black ribbon label">
             <i id="variants"></i>  <!-- displaying variants -->
          </div>
             <img src="/images/wireframe/image.png">
        </div>
      </div>`

I dont want names to be displayed all in one tag...instead...for every echoed data I want new column element..How should I do that?

Any answer to this is much appreciable..

Upvotes: 1

Views: 37

Answers (1)

Riccardo
Riccardo

Reputation: 178

Instead of echoing each data you should put all the data in an object or an array and echo a json:

echo json_encode($data_array);

From the client side then you can get the answer and iterate it to put the content in different elements.

if (xhttp.readyState == 4 && xhttp.status == 200)
{
    var jsonResponse = JSON.parse(xhttp.responseText);
    var text = '';
    for(var key in jsonResponse)
    {
        text += '<p>'+jsonResponse[key]+'</p>';
    }
    document.getElementById("variants").innerHTML = text;
}

Upvotes: 1

Related Questions