0

My ajax script below, takes json_encoded values from php script. The PHP script contains single value and also arrays. For single values I've no issue as I use the first loop to loop through them. For array values, I've no idea on how to loop through.

As far as i know, comma separated values can be put into array by split(',').But for my case, it doesn't output anything. Where's my mistake in the second for loop?

My full script:

 $("#receipt").on("click",function()
 {
     var ele = $(".header_tbl tbody tr").children().length;

     if(ele !=0)
     {
        $("#after_cash_cart_form").submit(function(){
                var data = {
                  "action": "test"
                };
                data = $(this).serialize() + "&" + $.param(data);

                $.ajax({
                  type: "POST",
                  dataType: "json",
                  url: "submit_cart.php",
                  data: data,
                  success: function(data) {

                     for(var i=0;i < data.length; i++)
                     {
                         //alert(data[i].price.length);//outputs '3'
                         //data[i].price; //outputs 120,200,150
                         var array = data[i].price.split(",");

                         for (var j=0;j < array.length; j++)
                         {
                             alert(array[j]);//doesn't output anything
                         }

                     }

                  }

                });
                return false;
       });
     }else
     {
       alert("Your cart is empty.");
     }
 });
16
  • 1
    If data[i].price outputs 120,200,150, then data[i].price.length should not be 2. Commented Jan 11, 2016 at 15:32
  • 1
    I'm confused, you can't split an array Commented Jan 11, 2016 at 15:37
  • 1
    If you have something that outputs 120, 200, 150 in an alert, and it's length is 3, it's an array Commented Jan 11, 2016 at 15:38
  • 1
    Not according to what you've posted, but just do typeof data[i].price to find out Commented Jan 11, 2016 at 15:39
  • 1
    And arrays are objects, so you have an array Commented Jan 11, 2016 at 15:40

1 Answer 1

1

data[i].price is already an array, so you don't need to split(",") it.

Instead of

var array = data[i].price.split(",");

just use

var array = data[i].price;

and then the rest of your code should work.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.