简体   繁体   English

通过 jQuery 向/从 PHP 发送/接收数据

[英]Send/receive data via jQuery to/from PHP

I am using this code to make the user input a name to create a folder.我正在使用此代码让用户输入名称以创建文件夹。 I have modified the code to try and send the form data via jQuery and receive the success/failure message from PHP through jQuery.我已修改代码以尝试通过 jQuery 发送表单数据,并通过 jQuery 从 PHP 接收成功/失败消息。

However, when I enter the name of the folder, nothing happens.但是,当我输入文件夹的名称时,什么也没有发生。 No folder is created nor any error displayed.没有创建文件夹,也没有显示任何错误。 Firebug does not show any error either. Firebug 也没有显示任何错误。

This is the code I have till now:这是我到目前为止的代码:

create.php:创建.php:

<html>
<head><title>Make Directory</title></head>
<body>
<div id="albumform">
    <form id="album_form" method="post" action="createAlbum.php" enctype="multipart/form-data">
        <p id="message" style="display:none;">
        <?php echo (isset($success)?"<h3>$success</h3>":""); ?>
        <?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>
        </p>
        <input type="text" id="create_album" name="create_album" value="" />
        <input type="button" onclick="return checkForm('album_form');" id="btn_album" name="btn_album" value="Create" />
    </form>
</div>
</body>
</html>

  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> 
  <script type="text/javascript">
  /* $("#btn_album").click(function() { */
                function checkForm(form) {
                    //create post data
                      var postData = { 
                        "create_album" : $("#create_album").val()
                      };

                      //make the call
                      $.ajax({
                        type: "POST",
                        url: "createAlbum.php",
                        data: postData, //send it along with your call
                        success: function(response){
                            $('#message').fadeIn();
                        }
                      });
                /* });   */
                }
  </script>

createAlbum.php: createAlbum.php:

<?php
/**********************
File: createDir.php
Author: Frost
Website: http://www.slunked.com
***********************/

// set our absolute path to the directories will be created in:
$path = $_SERVER['DOCUMENT_ROOT'] . '/web/photos/images/';


if (isset($_POST['btn_album'])) {
    // Grab our form Data
    $dirName = isset($_POST['create_album'])?$_POST['create_album']:false;

    // first validate the value:
    if ($dirName !== false && preg_match('~([^A-Z0-9]+)~i', $dirName, $matches) === 0) {
        // We have a valid directory:
        if (!is_dir($path . $dirName)) {
            // We are good to create this directory:
            if (mkdir($path . $dirName, 0775)) {
                $success = "Your directory has been created succesfully!<br /><br />";
            }else {
                $error = "Unable to create dir {$dirName}.";
            }
        }else {
            $error = "Directory {$dirName} already exists.";
        }
    }else {
        // Invalid data, htmlenttie them incase < > were used.
        $dirName = htmlentities($dirName);
        $error = "You have invalid values in {$dirName}.";
    }
}
?>

The ajax request has a bad habit of failing silently. ajax 请求有静默失败的坏习惯。 You should use jQuery post and take advantage of.success(), .complete(), and.error() functions to track your code.您应该使用 jQuery 帖子并利用 .success()、.complete() 和 .error() 函数来跟踪您的代码。 Also use the console.log() to check if the parameters are sent corectly.还可以使用 console.log() 检查参数是否正确发送。 I'll try out the code myself to see the problem.我将自己尝试代码以查看问题。

http://api.jquery.com/jQuery.post/ http://api.jquery.com/jQuery.post/

Due to the nature of the $.ajax request, $_POST['btn_album'] is not sent.由于 $.ajax 请求的性质,不会发送 $_POST['btn_album']。 So your php file gets here所以你的 php 文件到这里

if (isset($_POST['btn_album'])) {

and returns false.并返回假。

also you need to echo $error to get a response.您还需要回显 $error 以获得响应。

There are at least two seperate problems with your code:您的代码至少有两个单独的问题:

In the php-file, you check if $_POST['btn_album'] is set.在 php 文件中,您检查是否设置$_POST['btn_album'] This field is not sent as it is not part of your ajax-request (You're only sending "create_album": $("#create_album").val() ).此字段不发送,因为它不是您的 ajax 请求的一部分(您只发送"create_album": $("#create_album").val() )。 So the code that creates the folder is never executed.所以创建文件夹的代码永远不会执行。

Another problem is the part另一个问题是零件

    <?php echo (isset($success)?"<h3>$success</h3>":""); ?>
    <?php echo (isset($error)?'<span style="color:red;">' . $error . '</span>':''); ?>

in your response-message.在您的回复消息中。 This code is evaluated when the page loads, not during your ajax-request, so the php-variables $success and $error will always be undefined.此代码在页面加载时评估,而不是在您的 ajax 请求期间评估,因此 php 变量 $success 和 $error 将始终未定义。 You have to return those response-messages as response to the actual request and then use javascript to display them.您必须将这些响应消息作为对实际请求的响应返回,然后使用 javascript 来显示它们。

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

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