Weird php/jquery behavior with bool variables
Permalink
I have 3 blocks on a page. A value 'show_submit_error' is set in the block form as a tick box. Nothing special here. Block 1 has '1', block 2 has '1', block 3 has '0'. Block 3 is the last one in the order of appearance.
controller view():
view.php:
view.js:
The page shows 1, 1, 0 - same as set.
The first JS log shows the same 1, 1, 0 - same.
But after submitting the form the JS log shows all 0, 0, 0!
I can't figure out why. Tests show that after submitting the form the log always shows the value set in the very last block, regardless of what previous blocks are set to. Why?
Thank you.
controller view():
$this->set('show_submit_error', $this->show_submit_error); $jq_data = ['jq_test' => $this->show_submit_error]; $this->set('jq_data', json_encode($jq_data, JSON_UNESCAPED_UNICODE));
view.php:
view.js:
$(function(){ $.each($('.contact-form'), function(index, element){ var buid = $(element).attr('data-buid'); var attr_data = $(element).attr('data-jq'); jq_data = $.parseJSON(attr_data); console.log(jq_data.jq_test); form.submit(function(e) { e.preventDefault(); e.stopPropagation(); console.log(jq_data.jq_test); }); }); });
The page shows 1, 1, 0 - same as set.
The first JS log shows the same 1, 1, 0 - same.
But after submitting the form the JS log shows all 0, 0, 0!
I can't figure out why. Tests show that after submitting the form the log always shows the value set in the very last block, regardless of what previous blocks are set to. Why?
Thank you.
Any ideas why that happens?
Your form submit function is not running when you give jq_data a value, it is only running later when you submit the form. So you are giving jq_data a value and outputting it in the console 3 times. And each time you are declaring the submit function which is just waiting to be used.
When you finally submit your form the function grabs jq_data with whatever value it has at that time and that's the last one you set.
If you want all 3 values you should make jq_data an array and push your values to it on each loop. Then declare the form submit function outside of the loop and make it use jq_data hich is now an array with 3 values in it
When you finally submit your form the function grabs jq_data with whatever value it has at that time and that's the last one you set.
If you want all 3 values you should make jq_data an array and push your values to it on each loop. Then declare the form submit function outside of the loop and make it use jq_data hich is now an array with 3 values in it