Search code examples
phpmysqlfunctiononclickarea

How to call a php function that queries mysql from within map area using onclick


I have 2 php pages. The first php page has a function that queries MySQL. The second php page calls the function.

The function that queries MySQL works correctly when called by the second php page:

`<?php myfunction($user_id); ?>`

However I cannot seem to get the function to NOT trigger when the second php page loads and instead trigger when the user clicks inside the rectangular coordinates of an area in a map on that second page through onclick:

 `<map id="map_id_01" name="map_name_01"><area shape="poly" id="area_id_01" class="" title="area_title_01" onclick="myfunction($user_id)" coords="360,236,696,236,696,448,360,448,360,237"/></map>` 

Not sure how best to approach this and would be grateful for any ideas.


Solution

  • You need to use a combination of javascript and php. The user clicks on the rectangle, that triggers a javascript function that makes an ajax call to another page which then runs the php function and returns the result back to the original page and then you act upon that result in javascript, be it showing it to the user by placing it in a div or executing other functions. PHP is run server side which means as soon as the page is called by the user all of the php code is executed.

    Edit To show Code:

    <map id="map_id_01" name="map_name_01"><area shape="poly" id="area_id_01" class="" title="area_title_01" onclick="myfunction()" coords="360,236,696,236,696,448,360,448,360,237"/></map>
    <script type='text/javascript'>
        var userId = '<?php echo $user_id; ?>';
        function myFunction() {
            $.ajax({
                async: false,
                type: 'POST',
                url: 'run_function.php',
                data: 'user_id=' + userId,
                dataType: 'json',
                success: function(msg) {
                    if(msg.success) {
                       //Do whatever you want to with the return message here
                    } else {
                       alert('failed to run the php function because: ' + msg.message);
                    }
                 }
            });
        </script>
    

    Then in run_function.php...

    $user_id = $_REQUEST['user_id'];
    if($return = myfunction($user_id)) {
        $reply['success'] = true;
        $reply['message'] = $return;
    } else {
        $reply['success'] = false;
        $reply['message'] = 'Failed to run function' // whatever error message you want
    }
    echo json_encode($reply);
    

    **NOTE: this is a very simplistic example of using javascript to run php functions and acting upon their reply. you will probably need to edit this code to get the desired result. Also to run $.ajax you need to have jquery included in your html. if you do not lookup xmlhttprequest for javascript