0

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();
})
7
  • 1
    You have to create the poz.positions property before you can push onto it. Commented Jan 5, 2022 at 19:53
  • var poz = {positions: []} Commented Jan 5, 2022 at 19:55
  • Aren't you getting an error saying that undefined has no property push? Commented Jan 5, 2022 at 19:56
  • Hi Barmar - yes I am. I should have mentioned that. Just didn't know how to correct it Commented Jan 5, 2022 at 19:58
  • Ahhh got it. Thank you. I also had a typo. Still cleaning it up Commented Jan 5, 2022 at 20:05

2 Answers 2

1

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

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

Comments

0

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.

2 Comments

Thanks for the info Ty
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.