简体   繁体   English

使用 AJAX 将变量传递给 PHP 脚本

[英]Passing variable to PHP script using AJAX

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Example Ajax PHP Form</title>
        <script type="text/javascript" src="//code.jquery.com/jquery-2.1.0.min.js"></script>
    </head>
    <body>
        
        <form id="my_form_id">
            Your Email Address: <input type="text" id="email" /><br>
            <input type="button" id="ddd">
        </form>
        
        
        <script>
            $(document).ready(function(){
                $('#ddd').click(function(e){
                    //Stop the form from submitting itself to the server.
                    e.preventDefault();
                    var email = $('#email').val();
                    console.log(email);
                    $.ajax({
                        type: 'post',
                        url: 'http://localhost/script.php',
                        data: {email: email},
                        success: function(data){
                          alert(data);  
                        }
                    });
                });
            });
        </script>
    </body>
</html>

Above is the code from my index.php file.以上是我的 index.php 文件中的代码。 My goal is to pass an email address from this php page to another page titled script.php.我的目标是将电子邮件地址从这个 php 页面传递到另一个名为 script.php 的页面。 My script.php code is:我的 script.php 代码是:

<?php
session_start();

$emailAddress = '';
if(isset($_POST['ddd'])){
    $emailAddress = $_POST['email'];
    echo "hi";
}

echo 'Received email was: ' .$emailAddress;
?>

When I run my index.php code it displays an alert with the email address being successfully passed through with the AJAX function.当我运行我的 index.php 代码时,它会显示一个警告,其中包含通过 AJAX 函数成功传递的电子邮件地址。 However, when I refresh my script.php page it doesn't display the email address.但是,当我刷新我的 script.php 页面时,它不会显示电子邮件地址。 I am trying to display the email address on the script.php page so I could insert it into a sql statement.我试图在 script.php 页面上显示电子邮件地址,以便我可以将其插入到 sql 语句中。 Any insight on what i'm doing wrong would be greatly appreciated.任何关于我做错了什么的见解将不胜感激。

Changing your button type to submit doesn't help in ajax.更改按钮类型以submit在 ajax 中没有帮助。 All you need is their ids.您只需要他们的 ID。

Image Result图像结果

And also you don't need ajax for your situation.而且您的情况也不需要ajax。 You will just need this window.location= to redirect the data to your script.php您只需要此window.location=将数据重定向到您的 script.php

This will be your index.php这将是你的 index.php

<!DOCTYPE html>
  <html>
     <head>
       <meta charset="UTF-8">
       <title>Example Ajax PHP Form</title>
       <script type="text/javascript" src="//code.jquery.com/jquery-2.1.0.min.js"></script>
     </head>
   <body>
      <form id="my_form_id">
          Your Email Address: <input type="text" id="email"  /><br>
          <input type="button" id="ddd">
      </form>
      <script>
        $(document).ready(function()
        {
            $('#ddd').click(function()
            {
                var email = $('#email').val();
                window.location="script.php?email=" + email;
            });
        });
      </script>
    </body>
 </html>

And then this will be your script.php.然后这将是您的script.php。 I removed your if condition 'cause it prevents to display your email data.我删除了您的 if 条件,因为它会阻止显示您的电子邮件数据。 POST will be changed to REQUEST to get the data from the url. POST 将更改为 REQUEST 以从 url 获取数据。

 <?php 
   session_start();
   $emailAddress = $_REQUEST['email']; 
   echo 'Received email was: ' .$emailAddress;
 ?>

If you want only 1 php file, then do this.如果您只需要 1 个 php 文件,请执行此操作。 Please review the changes.请查看更改。 Changing your button type to submit is a must and also the method=POST in your form.必须将按钮类型更改为submit并且表单中的method=POST也是必须的。 No need for id , just name .不需要id ,只需要name

<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8">
      <title>Example Ajax PHP Form</title>
  </head>
  <body>
      <form method="POST">
         Your Email Address: <input type="text" name="email" /><br>
         <input type="submit" name="ddd">
      </form>
  </body>
</html>

<?php
   session_start();
   if (isset($_POST['ddd']))
   {
       $emailAddress = $_POST['email'];
       echo 'Received email was: ' .$emailAddress;
   }
?>

请将输入更改为按钮 type="submit" 然后在 javascript 中,请检查 .click 以提交

your question is still not clear the script you provide working perfectly ..您的问题仍然不清楚您提供的脚本是否完美运行..

but in your second part of question :但在你问题的第二部分:

When I run my index.php code it displays an alert with the email address being successfully passed through with the AJAX function.当我运行我的 index.php 代码时,它会显示一个警告,其中包含通过 AJAX 函数成功传递的电子邮件地址。 However, when I refresh my script.php page it doesn't display the email address.但是,当我刷新我的 script.php 页面时,它不会显示电子邮件地址。 I am trying to display the email address on the script.php page so I could insert it into a sql statement.我试图在 script.php 页面上显示电子邮件地址,以便我可以将其插入到 sql 语句中。 Any insight on what i'm doing wrong would be greatly appreciated.任何关于我做错了什么的见解将不胜感激。

that's true after ajax success will alert data.在 ajax 成功后会提醒数据,这是真的。 but your asking after I refresh script.php it's should display the email address...但是您在我刷新 script.php 后询问它应该显示电子邮件地址...

after you refresh the script.php there's now any saved email address to be displayed.. before refreshing script.php you should save email in database or browser storage.刷新 script.php 后,现在将显示任何保存的电子邮件地址.. 在刷新 script.php 之前,您应该将电子邮件保存在数据库或浏览器存储中。

Third parts第三部分

so I could insert it into a sql statement所以我可以将它插入到 sql 语句中

why you want to display email address and after that you want to insert into database.. you can directly insert in database after ajax success.. example don't use it.为什么要显示电子邮件地址,然后要插入数据库.. ajax 成功后可以直接插入数据库.. 示例不要使用它。

$sql = "INSERT INTO table ".
               "(email) "."VALUES ".
               "('$email')";
               mysql_select_db('SOMEDB');
            $res = mysql_query( $sql, $conn );
         
            if(! $res ) {
               die('Could not enter data: ' . mysql_error());
            }
         
            echo "Entered data successfully\n";
            mysql_close($conn);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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