如何在php之后调用jquery函数?

时间:2014-12-19 12:03:11

标签: javascript php jquery

我希望在php插入查询成功执行后显示jquery sweet警告..但是每当我尝试调用jquery函数之后如果条件,没有工作..或警报出现在页面重新加载之前1-2秒表单提交并立即消失..仅适用于按钮onclick方法..

<html>
<head>
<script src="lib/sweet-alert.js"></script>
<link rel="stylesheet" href="lib/sweet-alert.css">
</head>

<body>
<form method="post">
  <label for="name">name</label>
  <input type="text" name="name" id="name" />
  <input type="submit" value="submit" name="submit" class="sub" id="sub" />

<?php
   $a=mysql_connect("localhost","root","");
   $a1=mysql_select_db("test",$a);

  if(isset($_POST['submit']))
  {
         $name=$_POST['name'];
         $i=mysql_query("insert into student (name) values ('$name')");
    if($i)
    {

        echo "<script>a();</script>";
    }
  }
 ?>

 <script type="text/javascript">
 function a(){
 swal("Here's a message!");
 };
</script>

</body>
</html>

4 个答案:

答案 0 :(得分:3)

您正在尝试混合两种不兼容的语言,PHP是服务器端,JQuery是客户端。一旦您的浏览器显示页面,PHP脚本就已经完成处理,因此您无法决定从PHP脚本与浏览器进行交互。

如果你想要这种功能,你需要从javascript页面使用Ajax。

答案 1 :(得分:0)

在php脚本之前放置javascript函数声明。

<script type="text/javascript">
 function a(){
 swal("Here's a message!");
 };
</script>
<?php
   $a=mysql_connect("localhost","root","");
   $a1=mysql_select_db("test",$a);

  if(isset($_POST['submit']))
  {
         $name=$_POST['name'];
         $i=mysql_query("insert into student (name) values ('$name')");
    if($i)
    {

        "<script>a();</script>";
    }
  }
 ?>

答案 2 :(得分:0)

<?php 
if($_REQUEST['submit']){
    $i = "yes";
    if($i == "yes"){
    echo "<script>alert('hiii');</script>";
    }
}
?>
<form action="" method="post">
<input type="submit" name="submit" value="submit">
</form>

答案 3 :(得分:0)

我有1个demo.php文件用于表单和警报。和demo1.php文件进行php查询。 我必须使用Ajax。 demo.php:

<html>
<head>
<script src="lib/sweet-alert.js"></script>
<link rel="stylesheet" href="lib/sweet-alert.css">
<script src="js/jquery-1.8.0.min.js"></script>
</head>

<body>
<form method="post" class="frm" id="myform" onSubmit="j1">
 <label for="name">name</label>
 <input type="text" name="name" id="name" />
 <input type="submit" value="submit" name="submit" class="sub" id="sub" />
</form>

 <script>

     function j1(){
     var query = $('#myform').serialize();
     var url = 'demo1.php';
     $.post(url, query, function (response) {

         swal({
    title: "Thank You!",
    type: "success",
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Okay'
    },
    function(isConfirm){
    if (isConfirm){
    window.location.replace('demo.php');
    } 
   });

   });

    }
   $("#myform").submit(function(){
    return false;
   });

  </script>
</body>
</html>

demo1.php:

<?php
   $a=mysql_connect("localhost","root","");
   $a1=mysql_select_db("test",$a);      

                 $name=$_POST['name'];
     $i=mysql_query("insert into student (name) values ('$name')");

 ?>