0

I am working with angular and I got into a problem in the JQuery section:

 console.log(sustancia); // responds with {data: "8", comprado: "5", usado: "5", fecha: "2019-10-02", documento: "1234", …} this is correct and its treated as an object

 console.log(JSON.stringify(sustancia)); // responds with {} making me unable to send it through a $.post

I tried to make it exactly as the previous code by pushing it into a array which gives the same problem

If I try to review it in the console log its working but if I try to use JSON.stringify it doesn't return anything.
I tried sending it through the $.post without the JSON.stringify but it didn't work.
here is some of the code:

$('.singlealta').on('mousedown',function(){
      var elementos = [];
      var sustancia = {};
      $('#editorial >tr').click(function(){
         var id_sustancia = $(this).find('.id_sustancia').val();
         var comprado   = $(this).find('.comprado').val();
         var usado   =$(this).find('.usado').val();
         var fecha    =$(this).find('.fecha').val();
         var tipo_documento   =$(this).find('.tipo_documento').val();
         var sedronar    =$(this).find('.sedronar').val();
        sustancia = 
          { data:id_sustancia,comprado:comprado,usado:usado,fecha:fecha,documento:tipo_documento,sedronar:sedronar}
          elementos.push(sustancia);
          console.log(sustancia); //returns {data: "8", comprado: "5", usado: "5", fecha: "2019-10-02", documento: "1234", …}
 })
 console.log(JSON.stringify(elementos)); //returns []
 console.log(JSON.stringify(sustancia)); //returns {}
 
 $.post("*myurl**/phpfile*",JSON.stringify(sustancia)); //sends {} to the php file
 $.post("*myurl**/phpfile*",JSON.stringify(sustancia)); //sends [] to the php file
 
 console.log(elementos); //returns an array with the sustancia object below
 console.log(sustancia); //still returns {data: "8", comprado: "5", usado: "5", fecha: "2019-10-02", documento: "1234", …}
       });


Before this i had another JQuery almost identical that works perfect

$('#modificacion').on('mousedown',function(){
      var elementos = [];
      var i =0;
      $('#editorial >tr').each(function(){
      var id_sustancia   =$(this).find('.id_sustancia').val();
      var comprado   =$(this).find('.comprado').val();
      var usado   =$(this).find('.usado').val();
      var fecha   =$(this).find('.fecha').val();
      var tipo_documento  =$(this).find('.tipo_documento').val();
      var sedronar   =$(this).find('.sedronar').val();
       if(i>=0){
 var sustancia = 
 { data:id_sustancia,comprado:comprado,usado:usado,fecha:fecha,documento:tipo_documento,sedronar:sedronar}
 elementos.push(sustancia);
 console.log(elementos);    
       }
 i=i+1;
      });
      $.post("*myurl**/phpfile*",JSON.stringify(elementos));
     });
     //this one works pefectly and is not so diferent

any idea of what can be causing the JSON.stringify to return [] & {}?
thanks in advance and sorry if I had grammar errors, spanish is my first language but i can't think of how to ask it.
Lok C
  • 393
  • 1
  • 4
  • 13
Yan
  • 3
  • 2
  • Could you provide us with a runnable snippet? – lealceldeiro Oct 31 '19 at 14:52
  • from your code it looks like this could be cause by your console.log being called before you add any data to your array and object. – whodeee Oct 31 '19 at 14:57
  • Possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Christian Vincenzo Traina Oct 31 '19 at 15:00
  • Just curious, but are you using the former AngularJS JavaScript framework, or the newer Angular framework? – Edric Oct 31 '19 at 15:19
  • I am using angular 6 or 7 i think. – Yan Oct 31 '19 at 16:37

1 Answers1

0

This happens because the variable just has value after of some action. With this, your variables just will has value after a click action

$('#modificacion').on('mousedown',function(){
    $('#editorial >tr').click(function(){
        ...
        sustancia = {data:id_sustancia ...}
        elementos.push(sustancia);
        console.log(sustancia);

        // With this, the 'sustancia' just has value after click on '#editorial >tr'
        // so, the jQuery call this call back.
        // The result is there here inside the variable is asingn 
    });

    // But here happens in another momment,
    // It is call when 'mousedown'
    // The 'mousedown' happens before of 'click' in 'tr'
    console.log(JSON.stringify(elementos)); //returns []
    console.log(JSON.stringify(sustancia));
});

The correct way is change your post to inside of 'click' action, like this:

$('#modificacion').on('mousedown',function(){
    $('#editorial >tr').click(function(){
        ...
        sustancia = {data:id_sustancia ...}
        elementos.push(sustancia);
        console.log(sustancia);

        // Now it works, because the click happens and asingn the variables
        $.post("*myurl**/phpfile*",JSON.stringify(sustancia)); //sends {} to the php file
        $.post("*myurl**/phpfile*",JSON.stringify(sustancia));
    });
});
willteam
  • 117
  • 7
  • It is still a bad idea to add an event listener (`click`) inside the event handling function of another event handler (`mousedown`). This was already wrong in original code of OP. You will end up with multiple event-handling assignments being fired after a single click. – Carsten Massmann Oct 31 '19 at 15:56
  • Yes, it is really bad idea. Is using a event inside of another `event`, and every create assignments every time.The correct way is remove these `mousedown`, and send using just in `click` – willteam Oct 31 '19 at 16:23
  • Thanks it fixed the issue. i just realized that after the mousedown i forgot the click event, thanks 4 pointing it out. – Yan Oct 31 '19 at 16:47