在JavaScript中执行PHP脚本

时间:2017-11-08 11:21:24

标签: javascript php

这是我的PHP页面:

<div class="whomfollow">
        <div class="umayknow">People you may know</div>
      <ul>
      <?php
            $result = $linkID1->query("select ud.UserID,ud.Name,ud.Company,ud.Designation,ud.UserType,up.ProfilePic from user_details ud join user_picture up on ud.UserID=up.UserID where ud.UserID!='$UserID' ORDER BY RAND() LIMIT 20")
            or
            die(mysqli_error());

            while($row = mysqli_fetch_array($result))
            {
                $UT1='';
                if($row['UserType']=='A')
                {
                    $UT1='Advertiser';
                }
                else if($row['UserType']=='P')
                {
                    $UT1='Publisher';
                }
        ?>
        <li class="postimage followimgconnections">
            <div class="pull-left"><a href="#"><?php echo "<img src=profile_pic/".$row['ProfilePic']." />"; ?></a></div>
            <div class="pull-left followboxcontent">
              <div><a href="#"><b><?php echo $row['Name']; ?></b></a></div>
              <div><a class="followsmall_content" href="#"><?php echo $UT1." - ".$row['Designation']." - ".$row['Company']; ?></a></div>
              <div class="followbtn"><button id="myBtn" onClick="connect(<?php echo $row[UserID]; ?>)">Connect</button></div>
            </div>
        </li>
        <?php
            }
        ?>
      </ul>
      </div>
      <div class="clear"></div>
    </div>
<div id="myModal" class="modal">
      <!-- Modal content -->
      <div class="modal-content">

        <p class="popupheading">Invitation Sent</p>
        <p class="popupcontent">Your invitation is on its way.</p>
        <div class="invidone"><a href="#" class="close">Done</a></div>
      </div>
    </div>

<script>
function connect(num) {
    var x = document.getElementById('myBtn');
    <?php
        $ID=num;
        $stts='IS';  //Invitation Sent
        $stmt = $linkID1->prepare("insert into user_connections set MyUserID=?, MyFriendsUserID=?, cstatus=?");
        $stmt->bind_param("sss", $UserID,$ID,$stts);
        $stmt->execute();
        $stmt->close();
    ?>
    modal.style.display = "block";
    }
</script>

现在一旦加载页面,JavaScript中的PHP部分就会自动执行,我希望在调用JavaScript时运行该PHP部分。如果不可能这样做,那么还有另一种方式吗?

2 个答案:

答案 0 :(得分:1)

<script>
function connect(num) {
var x = document.getElementById('myBtn');

$.post('/Script.php', {id: num});

modal.style.display = "block";
}

的script.php:

    $ID=$_POST['id'];
    $stts='IS';  //Invitation Sent
    $stmt = $linkID1->prepare("insert into user_connections set MyUserID=?, MyFriendsUserID=?, cstatus=?");
    $stmt->bind_param("sss", $UserID,$ID,$stts);
    $stmt->execute();
    $stmt->close();

答案 1 :(得分:0)

谢谢大家,使用AJAX解决了这个问题。

function connect(num) {
var x = document.getElementById('myBtn');

$.ajax({
type: "POST",
url: "request-connect.php?id="+num
})

modal.style.display = "block";
}