Send image in form with AJAX / PHP / Mysql

Asked

Viewed 163 times

2

I’m redoing a form for a website that I need to send an image of, but I’m not able to upload and I need your help. I’ve already searched and I can’t find the answer... Function:

function fBlog_Send(){
$.ajax({
    type:"GET",
    url:"ad_BL_Include2.php",
    data:{
        nCategoryID:$('#nCategoryID-Include-Blog').val(),
        sTitle:$('#sTitle-Include-Blog').val(),
        sKeywords:$('#sKeywords-Include-Blog').val(),
        sDescription:$('#sDescription-Include-Blog').val(),
        sPicture:$('#sPicture-Include-Blog').val()
    },
    success:function(data){
        $('#blog-include').html(data);
    }
});

HTML:

<?php include "include_Connection.php" ?>
<div class="blog-div-tabs">
    <form id="adm-form">
        <fieldset>
            <label class="category">
                <select id="nCategoryID-Include-Blog">
                    <?php
                    $sQuery = "SELECT * FROM tcategory";
                    $rRecord = mysqli_query($sConn, $sQuery);
                    while($rRow = mysqli_fetch_assoc($rRecord)){
                        ?><option value="<?php echo $rRow["nID"];?>"><?php echo $rRow["sDescription"];?></option><?php
                    };
                    ?>
                </select>
            </label>
            <div class="clear"></div>
            <label class="title">
                <input type="text" id="sTitle-Include-Blog" placeholder="Título">
            </label>
            <div class="clear"></div>
            <label class="keywords" >
                <input type="text" id="sKeywords-Include-Blog" placeholder="Referência">
            </label>
            <div class="clear"></div>
            <label class="description">
                <textarea id="sDescription-Include-Blog" placeholder="Descrição"></textarea>
            </label>
            <div class="clear"></div>
            <label class="picture">
                <input type="file" id="sPicture-Include-Blog" placeholder="Imagem" class="image" />
            </label>
            <div class="clear"></div>
            <center><a class="href-Link-1" data-type="submit" onclick="fBlog_Send()"><img src="img/Contact/btn-Submit.png" /><img src="img/All/arrow.png" alt=""></a></center>
        </fieldset>
    </form>
</div>

PHP:

<?php include "include_Connection.php" ?>
<?php
session_start();
$nUserID_                               = $_SESSION["SS_nUserID"];
if(isset($_GET['nCategoryID'])){
    $nCategoryID_                       = strtolower($_GET['nCategoryID']);
}else{
    $nCategoryID_                       = "";
}
if(isset($_GET['sTitle'])){
    $sTitle_                            = strtoupper($_GET['sTitle']);
}else{
    $sTitle_                            = "";
}
if(isset($_GET['sKeywords'])){
    $sKeywords_                         = strtoupper($_GET['sKeywords']);
}else{
    $sKeywords_                         = "";
}
if(isset($_GET['sDescription'])){
    $sDescription_                      = strtoupper($_GET['sDescription']);
}else{
    $sDescription_                      = "";
}
if(isset($_FILES['sPicture']['name'])){
    $sPicture_                          = $_FILES['sPicture']['name'];
}else{
    $sPicture_                          = "";
}
$dDate_                                 = date("Y-m-d");
if($_FILES['sPicture']['name'] <> ''){
    if(move_uploaded_file($_FILES['sPicture']['tmp_name'], $sPath.'Original/'.$_FILES['lURL1']['name'])){
        $sImg = imagecreatefromjpeg($sPath.'Original/'.$_FILES['sPicture']['name']);
        $nWidth = imagesx($sImg);
        $nHeight = imagesy($sImg);
        $nWidth_tmp = 480;
        $nHeight_tmp = 360;
        if($nWidth > $nWidth_tmp || $nHeight > $nHeight_tmp){
            if($nWidth < $nHeight){
                $nImageWidth = round(($nWidth * $nHeight_tmp) / $nHeight);
                $nImageHeight = $nHeight_tmp;
            }elseif($nWidth > $nHeight){
                $nImageWidth = $nWidth_tmp;
                $nImageHeight = round(($nHeight * $nWidth_tmp) / $nWidth);
            }else{
                $nImageWidth = $nWidth_tmp;
                $nImageHeight = $nHeight_tmp;
            }
        }else{
            $nImageWidth = $nWidth;
            $nImageHeight = $nHeight;
        }
        $nImg_ = imagecreatetruecolor($nImageWidth, $nImageHeight);
        imagecopyresampled($nImg_, $sImg, 0, 0, 0, 0, $nImageWidth, $nImageHeight, $nWidth, $nHeight);
        $sPath_ = $sPath."Zoom/".$_FILES['sPicture']['name'];
        imagejpeg($nImg_, $sPath_);

        $sImg = imagecreatefromjpeg($sPath.'Original/'.$_FILES['sPicture']['name']);
        $nWidth = imagesx($sImg);
        $nHeight = imagesy($sImg);
        $nWidth_tmp = 120;
        $nHeight_tmp = 90;
        if($nWidth > $nWidth_tmp || $nHeight > $nHeight_tmp){
            if($nWidth < $nHeight){
                $nImageWidth = round(($nWidth * $nHeight_tmp) / $nHeight);
                $nImageHeight = $nHeight_tmp;
            }elseif($nWidth > $nHeight){
                $nImageWidth = $nWidth_tmp;
                $nImageHeight = round(($nHeight * $nWidth_tmp) / $nWidth);
            }else{
                $nImageWidth = $nWidth_tmp;
                $nImageHeight = $nHeight_tmp;
            }
        }else{
            $nImageWidth = $nWidth;
            $nImageHeight = $nHeight;
        }
        $nImg_ = imagecreatetruecolor($nImageWidth, $nImageHeight);
        imagecopyresampled($nImg_, $sImg, 0, 0, 0, 0, $nImageWidth, $nImageHeight, $nWidth, $nHeight);
        $sPath_ = $sPath."Thumb/".$_FILES['sPicture']['name'];
        imagejpeg($nImg_, $sPath_);

        $sInsert = "INSERT INTO tpicture(nPhotoID, lURL, sDescription) VALUES ('$nPhotoID', '$lURL1', '$sDescription1')";
        mysql_query($sInsert);
    }
}
mysqli_query($sConn,"INSERT INTO tblog(nUserID,nCategoryID,sTitle,sKeywords,sDescription,dDate,sPicture) VALUES('$nUserID_','$nCategoryID_','$sTitle_','$sKeywords_','$sDescription_','$dDate_','$sPicture_')");
?>
  • What error are you having? It’s time to save the image ? The image reaches the server ?

  • I believe that this link can help you.

  • Marabesi, the image does not reach the server... The error says that the variable sPicture is undefined on line 31, which is the line: if($_FILES['sPicture']['name'] <> ''){ of the PHP file, that is, in my understanding it is not passing the would as file by ajax!

  • Daniel, none of this that you mentioned makes a mistake, I’ve done all the tests and they’re working properly.

1 answer

1

FIRST: The mistake in session_start();, happens because the header has been called before, put this function before the header.

SECOND: Every form that uploads images should come with your enctype specified for: enctype="multipart/form-data" and put the method="get".

THIRD: on the error Undefined Variable, what may be happening that none of your conditions is setting a value for $_FILES['sPicture']['name']. A workable solution would be to treat the information better, something like this:

<?php

if(isset($_POST['submit'])){ //ponha um name para seu submit
   $name = $_FILES["sPicture"]["name"];  //ponha um name para seu type="file"    
   $tmp_name = $_FILES['sPicture']['tmp_name'];    

    if (isset ($name)) { //Caso não seja null
        if (!empty($name)) { //Caso não seja vazio


           //Aqui ficaria seu código para a o upload


        } //fim do empty
    } //fim do isset
} //fim do submit
?>

Ready! Do all this and return an answer here.

  • Ok, I changed Session (but there was no error msg in Session!)... But your example above would give example if I was not using AJAX, when I use AJAX and pass the variables first to an AJAX function and then to a PHP, PHP is not identifying that the variable sPicture contains a file!

  • My example was only a supplement to your form and conditions, only with this you will do nothing. Só fiz identificar pequenas falhas no seu código que podem está gerando os erros. Você acrescentou o enctypeemethodao form? Nem umnameo seuinput file` had

  • Actually I changed the focus a little bit, I ended up using an iframe on site!

  • Anyway thanks for the help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.