dongsi2317 2018-04-02 02:19
浏览 70
已采纳

重复Ajax(Jquery方法)单击和图像未传递到服务器的提交

I'm having issues on submmiting a formdata to my server after a jquery based client side validation. i havebeen working on this since noon, i really need assistance.I had made a jquery slider with my login form, so after each input it slides to the next after validation, so i have two issues basically, one after each submit of a review.. 5 reviews are actually made, and two the image is not processed, i'm not certain it passes to my server because it is not saved on my harddrive.

Here Is My Simple HTml Form

 <form action="review.php" method="post" id="makeReview" enctype="multipart/form-data">
<!-- first slide start -->
<div class="makereview firstSlide">
<div id="myslides" > 
 <input type="text" id="reviewName"  name="reviewName"  placeholder="Name of Reviewee" pattern="[a-zA-Z0-9'.- ]+" maxlength="25" class="myForm">
 <br>
<button class="btn btn-info nextSlideOne" >
  <i class="glyphicon glyphicon-arrow-right"></i>
</button>
<br>
 <strong style="color: red;text-align: left;" class="errorOne"></strong>
  </div>
</div>
<!-- first slide ends-->

<!-- Second slide start -->
<div class="makereview secondSlide">
<div id="myslides">

 <input type="text" id="reviewLink"  name="reviewLink" placeholder="https://reviewee.com" pattern="[a-zA-Z/.0-9:]+" class="myForm" style="text-transform: lowercase;">
 <br>
 <button class="btn btn-info nextSlideTwo" >
  <i class="glyphicon glyphicon-arrow-right"></i>
</button>
<br>
 <strong style="color: red;text-align: left;" class="errorTwo"></strong>
  </div>
</div>

<!-- Second slide ends-->

<!-- third slide start -->
<div class="makereview thirdSlide">
<div id="myslides">

 <input type="file" class="myForm" name="image" id="reviewLogo" style="margin: auto">
 <br>
 <button class="btn btn-info nextSlideThree" >
  <i class="glyphicon glyphicon-arrow-right"></i>
</button>
<br>
 <strong style="color: red;text-align: left;" class="errorThree"></strong>
  </div>
</div>


<!-- third slide ends-->

<!-- fourth slide start -->
<div class="makereview fourthSlide">
<div id="myslides" >
<h3>Your Review</h3>
  <textarea class="myForm" name="reviewBody" minlength="200" maxlength="500" placeholder="Your review. minimum 200 Characters and maximum 500 Characters" rows="8" id="reviewBody" ></textarea>
 <br>
<button class="btn btn-info nextSlideFour">
  <i class="glyphicon glyphicon-arrow-right"></i>
</button>
<br>
 <strong style="color: red;text-align: left;" class="errorFour"></strong>
  </div>

</div>
<!-- fourth slide ends-->
<div class="makereview fifthSlide">
<div id="myslides" >
<br>
<br>
<br>
<br>
<br>
<br><br>
<button class="btn btn-info btn-large nextSlideFive">
  <i class="glyphicon glyphicon-send"></i> Verify And Submit
</button>
<br>
 <br>
 <h2 style="color:green;text-align: center;font-family: serif;" class="responseSuccess"></h2>
 <strong style="color:red;text-align: center;" class="responseError"></strong>
  </div>
</div>
</form>

ANd here is my ajax method in jquery(i extracted it from the larger code to aid reading), the larger code is below it

  $(nextFive).click(function(){
$(nextFive).fadeOut('linear')
var formData = $(form).serialize();
  $.ajax({
      type: 'POST',
      url: 'review.php',
      data: formData,
    })
  .done(function() {
      $('.responseSuccess').text('Thank You 
 Your Review Have Been Made');
    })
})

Here is the larger code(i don't think it's necessary here but for clarity)

<script type="text/javascript">
$(function(){
  // get the form
$('.scriptOnlyForm').css('visibility','visible')
  var form = $('#makeReview');
// get the buttons 
  var nextOne   = $('.nextSlideOne');
  var nextTwo   = $('.nextSlideTwo');
  var nextThree = $('.nextSlideThree');
  var nextFour  = $('.nextSlideFour');
  var nextFive  = $('.nextSlideFive');
//get the input fie;ds
  var inputOne   = $('#reviewName');
  var inputTwo   = $('#reviewLink');
  var inputThree = $('#reviewLogo');
  var inputFour = $('#reviewBody');
//get the divs
  var first   = $('.firstSlide');
  var second  = $('.secondSlide');
  var third   = $('.thirdSlide');
  var fourth  = $('.fourthSlide');
  var fifth   = $('.fifthSlide');
// get the error classess
  var errorOne   = $('.errorOne');
  var errorTwo   = $('.errorTwo');
  var errorThree = $('.errorThree');
  var errorFour  = $('.errorFour');
// by default slide up all divs except first div
$(second).slideUp('fast');
$(third).slideUp('fast');
$(fourth).slideUp('fast');
$(fifth).hide('fast');

$(nextOne).css('visibility','visible');
$(nextTwo).css('visibility','visible');
$(nextThree).css('visibility','visible');
$(nextFour).css('visibility','visible');

//start the submit fuction  
$(form).submit(function(e){
  // prevent form from submiting by default
  e.preventDefault()
// first slide work========================================================== starts


 $(nextOne).click(function(){
   if($('#reviewName').val() == ''){
   $(errorOne).html('Input The reviewee Name Please');
  $(inputOne).css('background','red');
  return false; 
 }
 else if($('#reviewName').val() != ''){
      $(first).slideUp('slow');
      $(second).slideDown('linear');  
 }
})

//first slide work============================================================  ends


// second slide work========================================================== starts

$pattern_1 = /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i;
  $pattern_2 = /^(www)((\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i;

 $(nextTwo).click(function(){
   if($('#reviewLink').val() == ''){
   $(errorTwo).html('Input The reviewee Website Url Please');
  $(inputTwo).css('background','red');
  return false;
 }

  if(!$pattern_1.test($('#reviewLink').val()) || !$pattern_2.test($('#reviewLink').val())){
    $(errorTwo).html('Input A Valid Url Of the reviewee Please');
    return false;
  }

 else if($('#reviewLink').val() != ''){
      $(second).slideUp('slow');
      $(third).slideDown('linear');    
 }
})
// second slide work============================================================  ends
// Third slide work========================================================== starts

    $(nextThree).click(function(){

 if($('#reviewLogo').val() == ''){

  $(errorThree).html('Input The reviewee Logo Or badge Please');
  $(inputThree).css('background','red');
  return false;
}else if($('#reviewLogo').val() != ''){
      $(third).slideUp('slow');
      $(fourth).slideDown('linear');
    }
})


// third slide work============================================================  ends


// fourth slide work========================================================== starts


  $(nextFour).click(function(){
if($('#reviewBody').val() == ''){
  $(errorFour).html('Write Your Review Please');
  $(inputFour).css('background','red');
  return false;
 }else if($('#reviewBody').val() != ''){
      $(fourth).slideUp('slow');
      $(fifth).slideDown('linear');

     }
 })

// fourth slide work============================================================  ends

// verify form================================start

$(nextFive).click(function(){
$(nextFive).fadeOut('linear')
var formData = $(form).serialize();
  $.ajax({
      type: 'POST',
      url: 'review.php',
      data: formData,
  })
  .done(function() {
      $('.responseSuccess').text('Thank You 
 Your Review Have Been Made');
    })
})
//verify form ================================== ends
})
})
</script>

Finally here is my php(it works well when i use a regular form with inputs and submit button, so i guess i problem don't lie here)

<?php 
    require 'header.php';
 ?>

<?php
   if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $reviewBody = review($_POST['reviewBody']);
    $reviewName = sanitizeString($_POST['reviewName']);
    $reviewLink= sanitizeString($_POST['reviewLink']);
      $reviewDate = date('Y-m-d');
      if(isset($_SESSION['firstname']) && isset($_SESSION['lastname'])){
         $reviewBy=$_SESSION['firstname'].' '. $_SESSION['lastname']; 
      }else{
         $reviewBy= "source-research_user_not_registered_hence_we_give_an_unimaginable_name_that_is_obviously_not_going_to_be_hacked_nor_found_by_anyone";
      }


    if(empty($reviewBody) || empty($reviewName) || empty($reviewLink)){
      die('Input all fields to make a review'); }
        else if(
        $reviewName && $reviewBody && $reviewLink){

          $sql = ("INSERT INTO `reviews` (reviewName, reviewBody ,reviewDate, reviewLink,reviewLike, reviewUnlike, reviewBy ) VALUES ('$reviewName', '$reviewBody' , '$reviewDate','$reviewLink', 0,0, '$reviewBy') ");
          $query=mysqli_query($conn,$sql); 
if(!$query) {
header('location:makreview.php');
}


if($query){
  $my = ("SELECT * FROM reviews where reviewName ='$reviewName' and reviewBody='$reviewBody' ");
$result = mysqli_query($conn, $my);

if(!$result){
   $sql = ( "DELETE FROM `reviews` WHERE `reviews`.`reviewName` = '$reviewName' AND `reviewBody` = '$reviewBody'");
  $query=mysqli_query($conn,$sql);
header('LOcation:dashboard.php');
}

if($result->num_rows){
  $row =$result->fetch_array(MYSQLI_ASSOC);
 $reviewId=$row['reviewId'];
}

if(!$result->num_rows){
   $sql = ( "DELETE FROM `reviews` WHERE `reviewName` = '$reviewName' AND `reviewBody` = '$reviewBody'");
  $query=mysqli_query($conn,$sql);

   die('could not process, <a href="makereview.php">Go back</a>');
}
}
   }


if (isset($_FILES['image']['name']) && isset($reviewId)){
$saveto = "reviews/".$reviewId.".jpg";
 $space='[\s]';
  $nospace='';
  $saveto = preg_replace($space,$nospace,$saveto);
move_uploaded_file($_FILES['image']['tmp_name'], $saveto);
$typeok = TRUE;
switch($_FILES['image']['type'])
{
case "image/gif": $src = imagecreatefromgif($saveto); break;
case "image/jpeg": // Both regular and progressive jpegs
case "image/pjpeg": $src = imagecreatefromjpeg($saveto); break;
case "image/png": $src = imagecreatefrompng($saveto); break;
default: $typeok = FALSE; break;
}
if ($typeok)
{
list($w, $h) = getimagesize($saveto);
$max = 900;
$tw = $w;
$th = $h;
}
if ($w > $h && $max < $w)
{
$th = $max / $w * $h;
$tw = $max;
}
elseif ($h > $w && $max < $h)
{
$tw = $max / $h * $w;
$th = $max;
}
elseif ($max < $w)
{
$tw = $th = $max;
}
$tmp = imagecreatetruecolor($tw, $th);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $tw, $th, $w, $h);
imageconvolution($tmp, array(array(-1, -1, -1),
array(-1, 16, -1), array(-1, -1, -1)), 8, 0);
imagejpeg($tmp, $saveto);
imagedestroy($tmp);
imagedestroy($src);
}

if(!file_exists($saveto) && !isset($reviewId)){
  $sql = ( "DELETE FROM `reviews` WHERE `reviews`.`reviewName` = '$reviewName' AND `reviewBody` = '$reviewBody'");
  $query=mysqli_query($conn,$sql);
}
header('Location:dashboard.php');
}

?>
  • 写回答

1条回答 默认 最新

  • doujiao8649 2018-04-02 03:22
    关注

    To solve your issue,

    first you need to note that you cannot submit image with ajax using form serialize. You need to replace var formData = $(form).serialize(); with var formData = new FormData(this);

    Your form submit ajax code becomes

    $(nextFive).click(function(){
    $(nextFive).fadeOut('linear')
    //var formData = $(form).serialize();
    var formData = new FormData(this);
      $.ajax({
        type: 'POST',
        url: 'review.php',
        data: formData,
        cache:false,
        contentType: false,
        processData: false,
      })
      .done(function() {
          $('.responseSuccess').text('Thank You 
     Your Review Have Been Made');
        })
    })
    

    In your PHP page "review.php", you can only retrieve your form element with $_POST, the uploaded image can be retrieved with $_FILES. You also need to use PHP's move_uploaded_file to save the file to your desired location from the temporary directory.

    Hope this helps. There are several solutions on this online

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料