简体   繁体   中英

Javascript method to trigger function on another php page to update MySQL

I have a php page that uses onclick in the rectangular coordinates of the area of a map.

When the user clicks in this area I need a function on another php page to update MySQL for that user_id

page_1.php - user is logged in as user_id

<map id="map_id_01" name="map_name_01">
<area shape="poly" id="area_id_01" class="" title="area_title_01" 
onclick="page_2.php myfunction" 
coords="360,236,696,236,696,448,360,448,360,237"/></map>

page_2.php

<?php myfunction($user_id); ?>

What JavaScript method would work on page_1.php to trigger the function on page_2.php

You can't just call a PHP function directly from a page. You see, the onclick property and other similar ones such as onblur call a JavaScript function! In order to call a function from another PHP page, what you need is to use AJAX.

Here, this question should be enough for you (and it seems to be a duplicate aswell): using jquery $.ajax to call a PHP function

However, make sure you're using jQuery for this one, but if you aren't, you can replace it with plain old AJAX like this:

xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", 'page_2.php', true);
xmlhttp.send('test');
//xmlhttp.responseText will return the response as a text, and xmlhttp.responseXML will return it as xml

assuming jquery, and a very basic example

function addMap(userid)
{
    $.ajax({
       type: "POST",
       url: "http://domain.com/page_2.php",
       data: "userid="+userid,
       success: function(msg){
         alert( "Data Saved: " + msg ); //Anything you want
       }
     });
}

page_2.php

if(!empty($_POST['userid'])){
myfunction($_POST['userid']);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM