简体   繁体   中英

Upload image and text by same form

When I upload image and text by separate form, its work well. But Its not work when I add together. My form text upload by js and image upload by a php file. And I think my problem in my form.

If I upload together with js, What change in my js and submit.php, which also add below.

Here is my form code that not work together

<form action="" method="post" id="cmntfrm" enctype="multipart/form-data">
<fieldset id="cmntfs">
<legend class="pyct">
What's your mind
</legend>
<input type="hidden" name="username" size="22" tabindex="1" id="author" value="'.$pname.'"/>
<input type="hidden" name="email" size="22" tabindex="2" id="email" value="'.$email.'"/>
<p><textarea name="comment" rows="10" tabindex="4" id="comment"></textarea></p>


<div id="ajaxuploadfrm">
<form action="uploadpostimg.php" method="post" enctype="multipart/form-data">
<b>Select an image (Maximum 1mb)</b>
<input type="file" name="url" id="url" />
</form>
</div>

<p><input type="submit" name="submit" value="Post comment" tabindex="5" id="submit"/></span></p>
</fieldset>             
<input type="hidden" name="parent_id" id="parent_id" value="0" />
<input type="hidden" name="tutid2" id="tutid" value="'.$tutid2.'" />
</form>

js

$(document).ready(function(){
var inputAuthor = $("#author");
var inputComment = $("#comment");
var inputEmail = $("#email");
var inputUrl = $("#url");
var inputTutid = $("#tutid");
var inputparent_id = $("#parent_id");
var commentList = $(".content > comment");
var commentCountList = $("#updatecommentNum");
var error = $("#error");
 error.fadeOut();

    function updateCommentbox(){
        var tutid = inputTutid.attr("value");
    //just for the fade effect
    commentList.hide();
    //send the post to submit.php
    $.ajax({
        type: "POST", url: "submit.php", data: "action=update&tutid="+ tutid,
        complete: function(data){
            commentList.prepend(data.responseText);
            commentList.fadeIn(2000);
        }
    });
}

   function updateCommentnum(){
   var tutid = inputTutid.attr("value");
    //just for the fade effect
    commentList.hide();
    //send the post to submit.php
    $.ajax({
        type: "POST", url: "submit.php", data: "action=updatenum&tutid="+ tutid,
        complete: function(data){
            commentCountList.html(data.responseText);
            commentList.fadeIn(2000);
        }
    });
}

    function error_message(){   
    error.fadeIn();
    }

    function checkForm(){
    if(inputAuthor.attr("value") && inputComment.attr("value") && inputEmail.attr("value"))
        return true;
    else
        return false;
      }

    //on submit event
$("#cmntfrm").submit(function(){
error.fadeOut();
if(checkForm()){
var author = inputAuthor.attr("value");
var url = inputUrl.attr("value");
var email = inputEmail.attr("value");
var comment = inputComment.attr("value");
var parent_id = inputparent_id.attr("value");
var tutid = inputTutid.attr("value");

        //we deactivate submit button while sending
        $("#submit").attr({ disabled:true, value:"Sending..." });
        $("#submit").blur();
        //send the post to submit.php
        $.ajax({
            type: "POST", url: "submit.php", data: "action=insert&author="+ author + "&url="+ url + "&email="+ email + "&comment="+ comment + "&parent_id="+ parent_id + "&tutid="+ tutid,
            complete: function(data){
                error.fadeOut();
                commentList.prepend(data.responseText);
                updateCommentbox();
                updateCommentnum();

                //reactivate the send button
                $("#submit").attr({ disabled:false, value:"Submit Comment!" });
                 $( '#cmntfrm' ).each(function(){
    this.reset();
}); 
}
         });
    }
    else //alert("Please fill all fields!");
           error_message();
    //we prevent the refresh of the page after submitting the form
    return false;
});
});

Submit.php

<?php header('Content-Type: charset=utf-8'); ?>
<?php

        include("db.php");
        include_once("include/session.php");
        switch($_POST['action']){
        case "update":
        echo updateComment($_POST['tutid']);         
        break;
        case "updatenum":
        echo updateNumComment($_POST['tutid']);      
        break;
        case "insert":
        date_default_timezone_set('Asia/Dhaka');
        echo insertComment($_POST['author'], $_POST['comment'], $_FILES['url']['name'], $_POST['email'], $_POST['tutid'], $_POST['parent_id'], $date = date("M j, y; g:i a"));
        break;
        }

function updateNumComment($tutid) { 
//Detail here
}   

function updateComment($tutid) {
//Detail here
}


function insertComment($username, $description, $url, $email, $qazi_id, $parent_id, $date ){
global $dbh;

//Upload image script that not work here when i try together so i took it at separate file and then tried with above form

    $output_dir = "comimage/";
    $allowedExts = array("jpg", "jpeg", "gif", "png","JPG");
    $extension = @end(explode(".", $_FILES["url"]["name"]));
        if(isset($_FILES["url"]["name"]))
        {
            //Filter the file types , if you want.
            if ((($_FILES["url"]["type"] == "image/gif")
                || ($_FILES["url"]["type"] == "image/jpeg")
                || ($_FILES["url"]["type"] == "image/JPG")
                || ($_FILES["url"]["type"] == "image/png")
                || ($_FILES["url"]["type"] == "image/pjpeg"))
                && ($_FILES["url"]["size"] < 504800)
                && in_array($extension, $allowedExts)) 
            {
                  if ($_FILES["url"]["error"] > 0)
                    {
                    echo "Return Code: " . $_FILES["url"]["error"] . "<br>";
                    }
                if (file_exists($output_dir. $_FILES["url"]["name"]))
                  {
                  unlink($output_dir. $_FILES["url"]["name"]);
                  } 
                    else
                    {
                    $pic=$_FILES["url"]["name"];
                    $conv=explode(".",$pic);
                    $ext=$conv['1'];    

                    $user = $_SESSION['username'];
                    //move the uploaded file to uploads folder;
                      move_uploaded_file($_FILES["url"] ["tmp_name"],$output_dir.$user.".".$ext);
                    $pic=$output_dir.$user.".".$ext;
                    $u_imgurl=$user.".".$ext;
                    }
            }   
            else{echo '<strong>Warning !</strong>  File not Uploaded, Check image' ;}
        }
      //Submit main comment
        if ($parent_id == 0){
      $username = mysqli_real_escape_string($dbh,$username);
      $description = mysqli_real_escape_string($dbh,$description);

      $sub = "Comment to";
      $query = "INSERT INTO comments_lite VALUES('','$qazi_id','0','$username','$email','$description','','$parent_id','$date')";
        mysqli_query($dbh,$query);

      } else {

        if ($parent_id >= 1){
                    global $dbh;    
      $username = mysqli_real_escape_string($dbh,$username);
      $description = mysqli_real_escape_string($dbh,$description);

      $sub2 = "Reply to";
        $query = "INSERT INTO comments_reply VALUES('','$qazi_id','0','$username','$email','$description','','$parent_id','$date')";
        mysqli_query($dbh,$query);

}
}
}
?>

on click of submit you can put the code in js you have to make change in the js file

$.post('phpapgename.php',data:jquerydata,function(){
})

in the .php page you can put your query to submit your data.

You cannot have nested form. Try to avoid it and separate out the forms as below. And while submitting any form if you data from other form, create a hidden fields in this form and submit it.

Another suggestion: Since you're working with javascript anyway, outsource the upload-form to an invisible div and make it pop up by clicking/hovering an upload-button or entering the last field of form1 or whatever.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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