通过ajax php上传图片

时间:2018-02-25 22:54:53

标签: php jquery ajax html5

我正在尝试通过php中的ajax上传图片,但我收到错误第28行/home/domainname/public_html/promotionform.php中的未定义索引:logouploader 我痛苦了3天,但我不明白为什么它在这里发生的是我的html表格

                            <form id="promotionForm" enctype="multipart/form-data">
                            <div class="form-group">
                                <div class="col-md-12">
                                    <label class="control-label" for="discount">Discount Offers* :</label>
                                    <input type="text" class="form-control" id="discount" placeholder="example 50 percent or 50 dollars" name="discount">
                                    <div class="alert alert-danger hidden mt-lg" id="dnameerrbox"></div>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-12">
                                    <label class="control-label" for="discountitem">Deal / Promo Item* :</label>
                                    <input type="text" class="form-control" id="discountitem" placeholder="example Biryani or All Food" name="discountitem">
                                    <div class="alert alert-danger hidden mt-lg" id="ditemerrbox"></div>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-12">
                                    <label class="control-label" for="website">website :</label>
                                    <input type="text" class="form-control" id="website" placeholder="example homesolver.ca" name="website">
                                    <div class="alert alert-danger hidden mt-lg" id="weberrbox"></div>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-12" id="newdate">
                                    <label class="control-label" for="expirydate">Promotion expires on* :</label>
                                    <input type="text" class="form-control td.active.active" id="expirydate" placeholder="yyyy/mm/dd" name="expirydate">
                                    <div class="alert alert-danger hidden mt-lg" id="proerrbox"></div>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-12">
                                    <label class="control-label" for="desc">Promotion / offers detailed description* :</label>
                                    <div class="alert alert-danger hidden mt-lg" id="deserrbox"></div>
                                    <textarea class="form-control" rows="5" id="desc" placeholder="Enter Promotion / offers description" name="desc"></textarea>
                                </div>
                            </div>
                            <div class="form-group">
                                <div class="col-md-12">
                                    <label for="logouploader">Upload Logo Only jpg / png</label>
                                    <input type="file" id="logouploader" name="logouploader">
                                    <p class="help-block">Max 600 kb.</p>
                                    <div class="alert alert-danger hidden mt-lg" id="exterrbox"></div>
                                </div>
                            </div>
                            <div class="col-md-12">
                                <div class="alert alert-danger hidden mt-lg" id="robotError"></div>
                                <div class="form-group">
                                    <div class="g-recaptcha" data-sitekey="6LdZU0QUAAAAABUUQVjOQLbRy6DVMP0kZuOPjg8B"></div>
                                </div>
                            </div>
                            <div><button type="button" id="promotionsubmit" class="btn btn-secondary btn-block">Free Promotion</button></div>
                            <div><button type="button" id="logout" class="btn btn-secondary btn-block mr-xs mt-sm">Logout</button></div>
                        </form>

我正在使用custom.js页面进行验证,这是我的jquery编码

                /*for business promotion*/
            var dis = /^[a-zA-Z 0-9.,%]*$/;
            $("#discount").keyup(function(){
                discount = $('#discount').val();
                if(!dis.test(discount)){
                    errbox = $("#dnameerrbox");
                    errcontent = "Only alphabets, numbers & % are allowed in discount field";
                    showerror(errbox, errcontent);
                }
                if(dis.test(discount)){
                    errbox = $("#dnameerrbox");
                    errcontent = "";
                    hideerror(errbox, errcontent);
                    discounterr = "no";
                }
            });
            var disitem = /^[a-zA-Z 0-9.,]*$/;
            $("#discountitem").keyup(function(){
                discountitem = $('#discountitem').val();
                if(!disitem.test(discountitem)){
                    errbox = $("#ditemerrbox");
                    errcontent = "Only alphabets, numbers are allowed in discount item field";
                    showerror(errbox, errcontent);
                }
                if(disitem.test(discountitem)){
                    errbox = $("#ditemerrbox");
                    errcontent = "";
                    hideerror(errbox, errcontent);
                    discountitemerr = "no";
                }
            });
            $("#website").keyup(function(){
                website = $('#website').val();
                if(!alphanumeric.test(website)){
                    errbox = $("#weberrbox");
                    errcontent = "https not allowed. write, for ex. homesolver.ca OR www.homesolver.ca";
                    showerror(errbox, errcontent);
                }
                if(alphanumeric.test(website)){
                    errbox = $("#weberrbox");
                    errcontent = "";
                    hideerror(errbox, errcontent);
                    websiteerr = "no";
                }
            });
            var todaydate = new Date();
                $("#expirydate").datepicker({
                    autoclose: true,  
                    format: "yyyy/mm/dd",
                    startDate: todaydate
                });
                $("#expirydate").change(function () {
                    expirydate = $("#expirydate").val();
                    expirydateerr = "no";
                });
            $("#desc").keyup(function(){
                desc = $('#desc').val();
                if(!alphanumeric.test(desc)){
                    errbox = $("#deserrbox");
                    errcontent = "Only alphabets & numbers are allowed in description field";
                    showerror(errbox, errcontent);
                }
                if(alphanumeric.test(desc)){
                    errbox = $("#deserrbox");
                    errcontent = "";
                    hideerror(errbox, errcontent);
                    descerr = "no";
                }
            });
            var ext;
            $("#logouploader").change(function(){
                ext = $('#logouploader').val().split('.').pop().toLowerCase();
                if ($.inArray(ext, ['png','jpg','jpeg']) == -1){
                    errbox = $("#exterrbox");
                    errcontent = "Only png , jpg & jpeg are allowed in logos field";
                    showerror(errbox, errcontent);
                    $("#logouploader").val("");
                }
                else{
                    errbox = $("#exterrbox");
                    errcontent = "";
                    hideerror(errbox, errcontent);
                    logouploader = $("#logouploader").val();
                }
            });
            $("#promotionsubmit").click(function(){
                if((discounterr != "no") || (discountitemerr != "no") || (expirydateerr != "no") ||(descerr != "no")){
                    errbox = $("#robotError");
                    errcontent = "All * fields are mandatory";
                    showerror(errbox, errcontent);
                }
                if((discounterr == "no") && (discountitemerr == "no") && (expirydateerr =="no") && (descerr == "no")){
                    errbox = $("#robotError");
                    errcontent = " ";
                    hideerror(errbox, errcontent);
                    var fd = new FormData();
                    fd.append("discount",discount);
                    fd.append("discountitem",discountitem);
                    fd.append("website",website);
                    fd.append("expirydate",expirydate);
                    fd.append("desc",desc);
                    fd.append("logouploader",logouploader);
                    fd.append("recaptcha",grecaptcha.getResponse());
                $.ajax({
                    url:"promotionform.php",
                    method:"POST",
                    data : fd,
                    contentType: false,
                    processData: false,
                    cache: false,
                    success: function(data){
                        if(data == "notok"){
                            grecaptcha.reset();
                            errbox = $("#robotError");
                            errcontent = "please verify you are not robot";
                            showerror(errbox, errcontent);
                        }
                        if(data == "large"){
                            grecaptcha.reset();
                            errbox = $("#robotError");
                            errcontent = "image is larger than 600 kb. Allowed size is 600 kb for logo";
                            showerror(errbox, errcontent);
                        }
                        if(data == "wrongext"){
                            grecaptcha.reset();
                            errbox = $("#robotError");
                            errcontent = "only jpg, jpeg and png are allowed for logo";
                            showerror(errbox, errcontent);
                        }
                        if(data == "notimage"){
                            grecaptcha.reset();
                            errbox = $("#robotError");
                            errcontent = "file is not an image";
                            showerror(errbox, errcontent);
                        }
                        if(data == "Sorry"){
                            grecaptcha.reset();
                            errbox = $("#robotError");
                            errcontent = "Sorry, your file was not uploaded.";
                            showerror(errbox, errcontent);
                        }
                        if(data == "done"){
                            grecaptcha.reset();
                            errbox = $("#robotError");
                            errcontent = " ";
                            hideerror(errbox, errcontent);
                            window.location='http://domainname.com/';
                        }
                    }
                });
                }
            });

从这里我将值传递给我的promotionform.php页面并在此页面中我试图将名称放在我的mysql表上也想尝试将图像放在我的文件夹中这里是我的代码

    <?php
session_start();
    if(isset($_POST['recaptcha'])){
        $secret = "****************";
        $response = $_POST['recaptcha'];
        $remoteip = $_SERVER['REMOTE_ADDR'];
        $url = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=$secret&response=$response&remoteip=$remoteip");
        $content = json_decode($url, TRUE);
        if($content['success'] ==1){
            function test_input($data) {
            $data = trim($data);
            $data = stripslashes($data);
            $data = htmlspecialchars($data);
            $data = strtolower($data);
            return $data;
            }
            $discount = test_input($_POST["discount"]);
            $discountitem = test_input($_POST["discountitem"]);
            $website = test_input($_POST["website"]);
            $expirydate = test_input($_POST["expirydate"]);
            $desc = test_input($_POST["desc"]);
            $filename;
            if(isset($_FILES['logouploader']['name'])){
                $filename = basename($_FILES['logouploader']['name']);
                $filename = test_input($filename);
            }
            $dir = "img/uploads/";
            $ext = strtolower(pathinfo($_FILES['logouploader'], PATHINFO_EXTENSION));
            $allowed =  array('jpeg','png' ,'jpg');
            if(!in_array($ext,$allowed) ) {
                echo "wrongext";
                $uploadOk = 0;
                exit;
            }
            if ($_FILES[$filename]["size"] > 600000) {
                echo "large";
                $uploadOk = 0;
                exit;
            }
            if ($uploadOk == 0) {
                echo "Sorry";
                exit;
            }
            $uploadOk = 1;
            if ($uploadOk == 1) {
                move_uploaded_file($_FILES[$filename]["tmp_name"], $dir/$filename);
                $servername = "localhost";
                $username = "*******";
                $password = "*******";
                try {
                    $conn = new PDO("mysql:host=$servername;dbname=********", $username, $password);
                    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
                    $query = "INSERT INTO webpromo (discount, dealitem, website, expirydate, description, logouploader) VALUES (?, ?, ?, ?, ?, ?)";
                    $statement = $conn->prepare($query);
                    $statement->execute(
                        array(
                        $discount,
                        $discountitem,
                        $website,
                        $expirydate,
                        $desc,
                        $filename
                        ) );
                        $conn = null;
                        exit;
                        echo "done";
                }
                catch(PDOException $e)
                {
                    echo "Connection failed: " . $e->getMessage();
                }
            }
        }
        if($content['success'] !=1){
            echo "notok";
            $conn = null;
            exit;
        }
        $conn = null;
        exit;
    }
?>

1 个答案:

答案 0 :(得分:0)

var Row_Index = $(this).closest('tr').index();
$(".sltable tbody tr").eq(Row_Index).show().find('input[name="ssl[]"]').prop("checked", false);

在上面的行中,您实际上正在检索文件名,您要传递给FormData对象的是File对象

logouploader = $("#logouploader").val();