提交→执行PHP脚本->提醒用户——同时保持在同一页面上


Submit -> Execute PHP script -> Alert User -- while staying on same page

我有一个带有两个提交按钮的页面,使用if ($_POST['action'] == 'Test SMS')来执行我的"测试短信"按钮的代码。我需要从PHP脚本执行代码,然后给出一个警告框,而不离开页面。

index . html

<form action="updateUserConfig.php" method="post">
<input type='submit' name='action' value='Test SMS' class='btn-test'>
<input type="submit" name="action" value="Save" class="btn btn-primary">
</form>

updateUserConfig.php

if ($_POST['action'] == 'Test SMS') { //action for Test SMS Button
   //grab ntid and phone from header
   if(isset($_POST['ntid'])) $ntid = $_POST['ntid'];
   if(isset($_POST['phone'])) $phone = $_POST['phone'];
   //using the notify_sms_users funtion from send_notification.php
   require 'send_notification.php';
   notify_sms_users(array($ntid), "", 4);
   //alert user that there message has been sent
   $alert = "Your message has been sent to " . $phone;
   echo '<script type="text/javascript">alert("'.$alert.'");';
   echo '</script>';
   header('Location: index.php');
} else {-----action for other submit button------}

我问过一个类似的问题,在执行php脚本后被标记为重复,而不离开当前页面,但能够想出一个解决方案,所以我想分享。

我能够通过在我的header('location: index.php?text=success)函数中添加URL查询字符串来实现这一点,然后使用JS,我能够使用if语句来查找查询字符串并警告,如果是这样的话。

index . html

<form action="updateUserConfig.php" method="post">
    <input type='submit' name='action' value='Test SMS' class='btn-test'>
    <input type="submit" name="action" value="Save" class="btn btn-primary">
</form>
<script type="text/javascript">
$(document).ready(function () {
    if(window.location.href.indexOf("settings=success") > -1) {
       alert("Your settings have been saved");
    }
    else if(window.location.href.indexOf("text=success") > -1) {
       alert("A SMS has been sent!");
    }
});
</script>

updateUserConfig.php

if ($_POST['action'] == 'Test SMS') { //action for Test SMS Button
   //grab ntid and phone from header
   if(isset($_POST['ntid'])) $ntid = $_POST['ntid'];
   if(isset($_POST['phone'])) $phone = $_POST['phone'];
   //using the notify_sms_users funtion from send_notification.php
   require 'send_notification.php';
   notify_sms_users(array($ntid), "", 4);
   header('Location: index.php?text=success');
} else {-----action for other submit button------}
    header('Location: index.php?settings=success');

这个解决方案的唯一缺点是,我不容易访问我的PHP $phone变量来告诉用户消息被发送到什么数字

AJAX是最适合这项工作的方法,因为您试图实现的是前端交互。Php是一种服务器端语言。

AJAX将表单数据传输到后端php脚本。一旦php脚本处理了服务器上的数据,它就可以将所需的数据返回给AJAX脚本。这有时使用JSON完成,特别是当您有多个变量时。
$formdata = array(
    'ntid' => $_POST['ntid'],
    'phone' => $_POST['phone']
);
return json_encode($formdata);
返回的JSON代码看起来像这样:
{"ntid":"NT ID","phone":"Phone number"}

类似的教程非常有用:[http://www.yourwebskills.com/ajaxintro.php] [1]

我发现,从你的主要项目中休息一下,花一点时间学习一下你想要实现的目标背后的机制,可以让你更快地解决问题。