Use a javascript variable in a php query

If you're a new user of AppGini, feel free to ask general usage questions, or look for answers here.
Post Reply
dathanasios
Veteran Member
Posts: 31
Joined: 2020-12-26 10:17

Use a javascript variable in a php query

Post by dathanasios » 2020-12-26 10:49

Hello to community.
I am a completely newbie in AppGini.
I am starting to build a simple app.
I have a invoice counter field in detail view.
Based on invoice type selection (1), upon pressed the "Get invoice counter" hyperlink (2), must retrieve its counter from database and update this field (3).
01.png
01.png (28.14 KiB) Viewed 9717 times
I tried the following code:

Code: Select all

function invoices_dv($selectedID, $memberInfo, &$html, &$args)
{
        // if record exists, don't get its counter
        if ($selectedID)
        {
            return;
        }
        else
	{
            ob_start();
            echo "<h4><a href='javascript:calculate_counter()'>Get invoice counter</a></h4>";
            ?>
            <script>
            function calculate_counter()
            {
                var inv_type   = $j('#inv_counter').val();
                var sql_string = "SELECT `counter` FROM `invoice_types` WHERE `id` = '" + inv_type + "';";
                alert(sql_string);
            }
            </script>
            
            <?php
            $form_code = ob_get_contents();
            ob_end_clean();
		
            $html .= $form_code;
        }
}
but it is not working.
Ideally, I want to add a custom button (4) next to invoice counter field, instead of hyperlink.

pbottcher
AppGini Super Hero
AppGini Super Hero
Posts: 1709
Joined: 2018-04-01 10:12

Re: Use a javascript variable in a php query

Post by pbottcher » 2020-12-26 11:46

Hi,

looking at your question I would have a suggestion, but I do not know if that could work for you.

1, If the counter for the invoice comes from the same table as the invoice type you could use the build-in AppGini function to have the Invoice counter as a lookup to the invoice_types table (field counter) and have it autofilled. This way, once you select the invoice type, the counter will be filled automatically.

2, If that does not fit and you could register for the change event of the invoice type field and use the id to call an ajax function to retrieve your counter for that id.
3, If you want to have it manually trigger, you could add a button to the invoice counter and add to the button a script that retrieves the value of the counter (see 2) and does not trigger the submit (return false).
Any help offered comes with the best of intentions. Use it at your own risk. In any case, please make a backup of your existing environment before applying any changes.

dathanasios
Veteran Member
Posts: 31
Joined: 2020-12-26 10:17

Re: Use a javascript variable in a php query

Post by dathanasios » 2020-12-26 11:59

@pböttcher
Thank you for your reply.
The suggestion 3 fit my needs.
I am looking for a piece of code, how to embed a button next to field and how to set up correctly the trigger, read the value and update the field.
Actually I am trying to do this, but my code is not working:

Code: Select all

            function calculate_counter()
            {
                var inv_type   = $j('#inv_counter').val();
                var sql_string = "SELECT `counter` FROM `invoice_types` WHERE `id` = '" + inv_type + "';";
                var x = '<?php $qte = chr(34); $result = sqlValue($qt' + sql_string + '$qte); echo $result; ?>';
                alert(x);
            }
The error is in the line:

Code: Select all

var x = '<?php $qte = chr(34); $result = sqlValue($qt' + sql_string + '$qte); echo $result; ?>';

pbottcher
AppGini Super Hero
AppGini Super Hero
Posts: 1709
Joined: 2018-04-01 10:12

Re: Use a javascript variable in a php query

Post by pbottcher » 2020-12-26 16:12

Hi,

I dont think you can mix the javascript code and the PHP code like you want do that as the javascript will be executed on the client side once the page is created and has no backreferece to the (server-side) PHP code.

So what you can try is:

add to the hooks/TABLENAME-dv.js

Code: Select all

$j(function() {
	$j('#fieldid').css({"width":"100%","max-width":" calc(100% - 44px)","display": "inline-block"}).after('<button type="button" class="btn btn-success hspacer-md" id="get_invoice_button" title="Get Invoice"><i class="glyphicon glyphicon-plus-sign"></i></button>');
	$j('#get_invoice_button').on('click', function () {
     		var inv_type = $j('#inv_counter').val();
		$j.ajax({
			url: 'ajax_get_invoice_id.php?id='+inv_type,
			success: function(id) {
				$j('#fieldid).val(id);
			}
		});
	})
})
Now add an ajax_get_invoice_id.php file to your root directory with something like :

Code: Select all

<?php
	$currDir=dirname(__FILE__);
	include_once("$currDir/lib.php");

	/* maintenance mode */
	handle_maintenance();

	/* capture input */
	$inv_type = $_Request['id'];
	$sql_string = "SELECT `counter` FROM `invoice_types` WHERE `id` = '".$inv_type."';
	$result = sqlValue($sql_string);

	/* return result */
	echo $result;
Replace TABLENAME and fieldid with our correct settings.

Code is not tested, so there might be typos, but it should give you a start.
Any help offered comes with the best of intentions. Use it at your own risk. In any case, please make a backup of your existing environment before applying any changes.

dathanasios
Veteran Member
Posts: 31
Joined: 2020-12-26 10:17

Re: Use a javascript variable in a php query

Post by dathanasios » 2020-12-27 10:43

@pböttcher
Thank you very much for your response.
The ajax_get_invoice_id.php part after correcting some typos, add type: "POST" in ajax is working smoothly, as a function called by a hyperlink. :D

The hooks/invoices-dv.js does not display the button.
I also tried to add the code under the

Code: Select all

function invoices_dv($selectedID, $memberInfo, &$html, &$args)
function on invoices.php file.
The button is displayed with the following code, but the result is bad and the click is not working:

Code: Select all

function invoices_dv($selectedID, $memberInfo, &$html, &$args)
    {
        ob_start();
        // echo "<h4><a href='javascript:my_counter()'>Υπολογισμός μετρητή εφαρμογής</a></h4>";
    ?>

        <!-- <script> -->

        $j(function()
        {
            $j('#invoice_counter').css({"width":"100%","max-width":" calc(100% - 44px)","display": "inline-block"}).after('<button type="button" class="btn btn-success hspacer-md" id="get_invoice_button" title="Get Invoice"><i class="glyphicon glyphicon-plus-sign"></i></button>');
            $j('#get_invoice_button').on('click', function ()
            {
                var inv_type = $j('#invoice_type').val();
                $j.ajax(
                {
                    type: "POST",
                    url: 'ajax_get_invoice_id.php?myid='+inv_type,
                    success: function(myid)
                    {
                        $j('#invoice_counter).val(myid);
                    }
                });
            })
        })

            <!-- </script> -->
            
           <?php 
            $form_code = ob_get_contents();
           ob_end_clean();
		
            $html .= $form_code;
    }
02.png
02.png (34.67 KiB) Viewed 9661 times
And, another trivial question.
I tried to get the text of a lookup Invoice type field.
I tried

Code: Select all

alert($j('#invoice_type-container').text().trim());  [b]=> undefined[/b}
alert($j('#invoice_type').attr('text'));  [b]=> undefined[/b}
alert($j('#invoice_type').attr('src')); [b]=> empty string[/b}
Which is the correct way to retrieve the text?
Regards,

pbottcher
AppGini Super Hero
AppGini Super Hero
Posts: 1709
Joined: 2018-04-01 10:12

Re: Use a javascript variable in a php query

Post by pbottcher » 2020-12-27 11:55

Hi,

you need to declare the javascript as javascript. You put comment there which causes the script to appear as text.
So use

Code: Select all

function invoices_dv($selectedID, $memberInfo, &$html, &$args)
    {
        ob_start();
        // echo "<h4><a href='javascript:my_counter()'>Υπολογισμός μετρητή εφαρμογής</a></h4>";
    ?>

        <script>

        $j(function()
        {
            $j('#invoice_counter').css({"width":"100%","max-width":" calc(100% - 44px)","display": "inline-block"}).after('<button type="button" class="btn btn-success hspacer-md" id="get_invoice_button" title="Get Invoice"><i class="glyphicon glyphicon-plus-sign"></i></button>');
            $j('#get_invoice_button').on('click', function ()
            {
                var inv_type = $j('#invoice_type').val();
                $j.ajax(
                {
                    type: "POST",
                    url: 'ajax_get_invoice_id.php?myid='+inv_type,
                    success: function(myid)
                    {
                        $j('#invoice_counter).val(myid);
                    }
                });
            })
        })

            </script>
            
           <?php 
            $form_code = ob_get_contents();
           ob_end_clean();
		
            $html .= $form_code;
    }
I dont think you need the type POST for the ajax call.

Is the invoice type a lookup (as it looks like)?
Why do you need the text of the lookup? Usually you would need the PK of the record.
To retrieve the text you can use

Code: Select all

$j('#s2id_invoice_type-container').find('.select2-chosen').text()
Any help offered comes with the best of intentions. Use it at your own risk. In any case, please make a backup of your existing environment before applying any changes.

dathanasios
Veteran Member
Posts: 31
Joined: 2020-12-26 10:17

Re: Use a javascript variable in a php query

Post by dathanasios » 2020-12-27 12:49

With your suggestion i can retrieve the text correctly. Thanks!
If a just uncomment the <script> and </script> tags from the code I posted above the button disappears.

pbottcher
AppGini Super Hero
AppGini Super Hero
Posts: 1709
Joined: 2018-04-01 10:12

Re: Use a javascript variable in a php query

Post by pbottcher » 2020-12-27 13:25

Can you check if $j('#invoice_counter') is the correct selection for your input element?
Also, do you have any error in the console?
Any help offered comes with the best of intentions. Use it at your own risk. In any case, please make a backup of your existing environment before applying any changes.

dathanasios
Veteran Member
Posts: 31
Joined: 2020-12-26 10:17

Re: Use a javascript variable in a php query

Post by dathanasios » 2020-12-27 15:10

Here is the code.

Code: Select all

<!-- Field: Invoice counter -->
<div class="form-group invoices-invoice_counter">
    <hr class="hidden-md hidden-lg">
    <label for="invoice_counter" class="control-label col-lg-3">Invoice counter<span class="text-danger">*</span></label>
    <div class="col-lg-9">
	<input maxlength="" type="text" class="form-control" name="invoice_counter" id="invoice_counter" value="" required>
     </div>
</div>
In the console there is not a critical error.
04.png
04.png (65.17 KiB) Viewed 9637 times
Give some time.
I will rewrite the project from scratch, more carefully in order to avoid typos.
In any case is a very simple, experimental project, so it will not take so much

dathanasios
Veteran Member
Posts: 31
Joined: 2020-12-26 10:17

Re: Use a javascript variable in a php query

Post by dathanasios » 2020-12-27 16:55

@pböttcher
I rewrite the app and Everything is run smoothly!
05.png
05.png (23.49 KiB) Viewed 9624 times
Thank you very much for your help!

pbottcher
AppGini Super Hero
AppGini Super Hero
Posts: 1709
Joined: 2018-04-01 10:12

Re: Use a javascript variable in a php query

Post by pbottcher » 2020-12-27 19:25

Glad it works. Have fun and stay healthy.
Any help offered comes with the best of intentions. Use it at your own risk. In any case, please make a backup of your existing environment before applying any changes.

dathanasios
Veteran Member
Posts: 31
Joined: 2020-12-26 10:17

Re: Use a javascript variable in a php query

Post by dathanasios » 2020-12-27 19:32

You to!
Thank you very much again!

Post Reply