Home > other >  jQuery Each Loop to push data into JSON Object
jQuery Each Loop to push data into JSON Object

Time:01-06

Can anyone suggest what I am doing wrong here. I have several elements on screen with class .cp_select. I need to loop through them and grab the attributes of "x" and "y". This by itself works fine. Then I need to assemble a JSON obj with a sub array child positions and push each looping x/y set into it. I'm then going to use the array in PHP with json_decode(), loop through that child positions and process it on the PHP side. I just can't seem to figure it out. Any ideas?

$(".pix_select_btn").click(function() {
    
    var poz = {}
    var poz_xy = {}
    $(".cp_select").each(function() {
        
        var pix = $(this)
        poz_xy = {"x" : pix.attr("x"), "y" : pix.attr("y")};
        poz['positions'].push(pos_xy)
                    
    });
    alert(JSON.stringify(poz))
    console.log();
})

CodePudding user response:

You have to create the array before you can push into it.

$(".pix_select_btn").click(function() {

  var poz = {positions: []}
  $(".cp_select").each(function() {

    var pix = $(this)
    var poz_xy = {
      "x": pix.attr("x"),
      "y": pix.attr("y")
    };
    poz.positions.push(pos_xy)

  });
  console.log(JSON.stringify(poz));
})

You can also simplify it by using map().

$(".pix_select_btn").click(function() {

  var poz = {
    positions: $(".cp_select").map(function() {
      var pix = $(this)
      return {
        "x": pix.attr("x"),
        "y": pix.attr("y")
      };
    }).get(); // .get() converts from jQuery object to array
  }
  console.log(JSON.stringify(poz));
})

CodePudding user response:

Remember that PHP runs in server and JS run in client, so you don't be able to use var poz in PHP.

You need to send a XHR request to catch the values in the server side.

  •  Tags:  
  • Related