使用ajax

时间:2015-07-06 17:05:23

标签: php ajax

我一直在尝试制作表单并通过ajax将数据发布到其他php文件中。这工作正常,很酷。发布的数据没有重新加载页面。但现在我已经在该表单中添加了文件上传,现在它无法正常工作。该错误表示未定义的索引:文件。我想这是因为我没有使用multipart / form-data。如何在不使用<form>标记的情况下执行此操作?我这样说是因为如果我使用<form>页面会重新加载。

这是我的代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Home | Facemash | Created by Incredible Saurav</title>

    <!-- core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/main.css" rel="stylesheet">

<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function sendContact() {
    var valid;  
    valid = validateContact();
    if(valid) {
        $.ajax({
        type:"POST",
        url: "req.php",
        data:'name1='+$("#name1").val()+'&email='+$("#email").val()+'&phone='+$("#phone").val()+'&file='+$("#file").val()+'&purpose='+$("#purpose").val()+'&message='+$("#message").val(),
        success: function(data){
        $("#mail-status").html(data);
        },
        error:function (){}
        });
    }
}

function validateContact() {
    var valid = true;   
    $(".demoInputBox").css('background-color','');
    $(".info").html('');

    if(!$("#name1").val()) {
        $("#name1-info").html("<a style='font-size:14px;float:right;border-radius:5px;background-color:#c52d2f;width:50%;text-align:center;padding:3px;color:white'>Required</a>");
        $("#name1").css('background-color','#FFFFDF');
        valid = false;
    }

    if(!$("#email").val()) {
        $("#email-info").html("<a style='font-size:14px;float:right;border-radius:5px;background-color:#c52d2f;width:50%;text-align:center;padding:3px;color:white'>Required</a>");
        $("#email").css('background-color','#FFFFDF');
        valid = false;
    }
    if(!$("#email").val().match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/)) {
        $("#email-info").html("<a style='font-size:14px;float:right;border-radius:5px;background-color:#c52d2f;width:50%;text-align:center;padding:3px;color:white'>Invalid</a>");
        $("#email").css('background-color','#FFFFDF');
        valid = false;
    }
    if(!$("#phone").val()) {
        $("#phone-info").html("<a style='font-size:14px;float:right;border-radius:5px;background-color:#c52d2f;width:50%;text-align:center;padding:3px;color:white'>Required</a>");
        $("#phone").css('background-color','#FFFFDF');
        valid = false;
    }
    if(!$("#file").val()) {
        $("#file-info").html("<a style='font-size:14px;float:right;border-radius:5px;background-color:#c52d2f;width:50%;text-align:center;padding:3px;color:white'>Required</a>");
        $("#file").css('background-color','#FFFFDF');
        valid = false;
    }
    if(!$("#message").val()) {
        $("#message-info").html("<a style='font-size:14px;float:right;border-radius:5px;background-color:#c52d2f;width:50%;text-align:center;padding:3px;color:white'>Required</a>");
        $("#message").css('background-color','#FFFFDF');
        valid = false;
    }
    if(!$("#purpose").val()) {
        $("#purpose-info").html("<a style='font-size:14px;float:right;border-radius:5px;background-color:#c52d2f;width:50%;text-align:center;padding:3px;color:white'>Are you kidding me ?</a>");
        $("#purpose").css('background-color','#FFFFDF');
        valid = false;
    }

    return valid;
}
</script>
    </head><!--/head-->
<body>
    <section id="contact-page">
        <div class="container">
            <div class="row contact-wrap"> 
                                <div id="frmContact">
                                <div id="mail-status"></div>

                    <div class="col-sm-5 col-sm-offset-1">
                        <div class="form-group">
                            <label style="font-size:15px">Name</label>
                            <span id="name1-info" class="info"></span>
                            <input type="text" name="name1" id="name1" class="form-control" placeholder="Please enter your Name">
                        </div>
                        <div class="form-group">
                            <label style="font-size:15px">Email</label>
                            <span id="email-info" class="info"></span>
                            <input type="email" name="email" id="email" class="form-control" placeholder="Please enter your Email">
                        </div>
                        <div class="form-group">
                            <label style="font-size:15px">Phone</label>
                            <span id="phone-info" class="info"></span>
                            <input type="number" name="phone" id="phone" class="form-control" placeholder="Please enter your Phone no.">
                        </div>

                    </div>
                    <div class="col-sm-5">
                         <div class="form-group">
                            <label style="font-size:15px">Purpose</label>
                            <span id="purpose-info" class="info"></span>
                            <select type="text" name="purpose" id="purpose" class="form-control" >
                              <option value="2">To add a Picture</option>
                              <option value="0">To remove a Picture</option></select>
                        </div>
                        <div class="form-group">
                            <label style="font-size:15px">Upload </label>
                            <span id="file-info" class="info"></span>
                            <input type="file" name="file" id="file" class="form-control">
                        </div>
                        <div class="form-group">
                            <label style="font-size:15px">Message</label>
                            <span id="message-info" class="info"></span>
                            <textarea name="message" id="message" required="required" class="form-control" rows="2" placeholder="Please enter your message" ></textarea>
                        </div>                        
                        <div class="form-group">
                            <button type="submit" name="submit" class="btn btn-primary btn-lg" onClick="sendContact();">Submit Message</button>
                        </div>
                    </div>

                </div> 
            </div>  <!--/.row-->
        </div><!--/.container-->
    </section><!--/#contact-page-->

    <script src="js/jquery.js"></script>
    <script src="js/bootstrap.min.js"></script>
    </body>
</html>

这是我发布的req.php文件:

<?php
 $purpose = $_REQUEST['purpose'];
 $name1 = $_REQUEST['name1'];
 $name = $_FILES['file']['name'];
 $tmp_name = $_FILES['file']['tmp_name'];
 $email = $_REQUEST['email'];
 $phone = $_REQUEST['phone'];
 $message = $_REQUEST['message'];
$data = "Name: $name1\nEmail: $email\nPhone: $phone\nPurpose: $purpose\nFilename: $name\nMessage: $message\n\n----------------------\n--------------------\n\n";

$fh = fopen("requests.txt", "a");

if(fwrite($fh,$data)==false)
{
    fclose($fh);
    echo "<p style='background-color:red;color:white;width:100%;padding:5px'>Error occurred while writing to file !</p>";
}
else
{
    fclose($fh);
        if (isset($name)) {
    if(!empty($name)) {
        $location = 'uploads/';
    if (move_uploaded_file($tmp_name, $location.$name)) {
        echo "<br><br><p style='background-color:green;color:white;width:100%;padding:5px'>Your picture was added successfully !</p>";
    }else{
        echo 'please chose a file.';
    }
    }
}
    echo "<br><br><p style='background-color:green;color:white;width:100%;padding:5px'>Your picture was added successfully !</p>";
}


?>

1 个答案:

答案 0 :(得分:-1)

如果您使用的是AJAX,则不需要表格,这是多余的。

你应该拥有的例子:

Html结构:

<div>
  <input type="text" id="name"/>
  <input type='file' accept='image/png,image/jpg,image/jpeg,image/bmp' id='image'>

  <button id="send">Send</button>
</div>

jQuery结构:

var image = null;

$(document).on('change', '#image', function(event)
{
   image = event.target.files;
});

$(document).on('click', '#send', function(event)
{
   event.stopPropagation();
   event.preventDefault();

   var data = new FormData();

   $.each(image, function (key, value) 
   {
      data.append('image', value);
   });

   data.append('name', $('#name').val());

   $.ajax(
   {
      url: yourUrl,
      type: 'POST',
      data: data,
      cache: false,
      processData: false,
      contentType: false,
      success: function(response)
      {

      }
   });
});

在PHP中,您只需要print_r($_FILES)print_r($_POST)知道您可以访问和使用哪些值。

但我现在可以告诉你,你将访问$_FILES['image'][],因为这是我设置为ID的名称。