我如何像本教程一样提交此表单?

时间:2017-01-21 01:29:04

标签: php ajax

我看过这个教程,并尝试了Form submit with ajax without refresh

当我在index.php中使用php代码时工作正常。但现在我添加了js并在reply.php中复制了php代码。它不工作。

我甚至不确定php是否以与ajax相同的方式工作。

有人请帮我在数据库中提交此表格。

的index.php

begin snippet:js hide:false console:true babel:false - >

<div id="comment-box">
<div class="form-group">

<form  method="post" id="reply"  enctype="multipart/form-data" style="width: 85%;"  >
<div class="input-group">


<input type="file" name="image2" class="file" id="imgInp"/>

<span class="input-group-btn">
        <button class="browse btn btn-primary input-md" type="button" ><i class="glyphicon glyphicon-picture"></i>I</button>
      </span>
<input   type="text" placeholder="say something" class="form-control" name="comment"/><br/>

<span class="input-group-btn">
 <button class="btn btn-info"   >submit</button>
 </span>

 </div>
 <div>
 <img id="blah" src="/final/images/blank.jpg"   style=" width:7%; float:left; " />
 </div>
</form>

</div>

<script type="text/javascript">
$(document).ready(function() {  

    // submit form using $.ajax() method

    $('#reply').submit(function(e){

        e.preventDefault(); // Prevent Default Submission

        $.ajax({
            url: 'reply.php',
            type: 'POST',
            data: $(this).serialize() // it will serialize the form data
        })
        .done(function(data){
            $('#fcomment-box').fadeOut('slow', function(){
                $('#comment-box').fadeIn('slow').html(data);
            });
        })
        .fail(function(){
            alert('Ajax Submit Failed ...');    
        });
    });




});
</script>




</div>

这里是php reply.php:

[注意:当它在同一个index.php中时,它工作正常。我刚刚在reply.php中复制了整个php代码。

&#13;
&#13;
<?php

  // these php variables are  from index.php   .   will this work now like  these are included  ?? 

$user =$_SESSION['user_email'];
$get_user = "select * from users where user_email='$user' ";
$run_user = mysqli_query($con,$get_user); 

$row = mysqli_fetch_array($run_user);

$user_id2 = $row['id'];
$user_name2 = $row['user_name'];


if( $_POST ){
	
	

	
	
	global $con;
global $user_id2;
$comment = $_POST['comment'];

$post_image2 = $_FILES['image2']['name'];
$image_tmp2 = $_FILES['image2']['tmp_name'];
$fileType = $_FILES["image2"]["type"];
$fileSize = $_FILES["image2"]["size"];
$fileErrorMsg = $_FILES["image2"]["error"]; // 0 for false... and 1 for true

$kaboom = explode(".", $post_image2); // Split file name into an array using the dot
$fileExt = end($kaboom); // Now target the last array element to get the file extension
			
			$post_image2 = preg_replace('#[^a-z.0-9]#i', '', $post_image2);

            $post_image2 = time().rand().".".$fileExt;	
			
			

date_default_timezone_set("America/New_York");
$date = date('Y-m-d H:i:s');

if ( $_FILES['image2']['name']=='') { 
    
	 $insert =" insert into comments (post_id,user_id,comment,author_name,date) values('$post_slug','$user_id2','$comment','$user_name2','$date' ) ";

$run = mysqli_query($con,$insert);
    
}


 else if($fileSize > 1048576) { // if file size is larger than 5 Megabytes
    echo "ERROR: Your file was larger than 1 Megabytes in size.";
     // Remove the uploaded file from the PHP temp folder
   
} else if ($fileErrorMsg == 1) { // if file upload error key is equal to 1
    echo "ERROR: An error occured while processing the file. Try again.";
    
} 

else if (preg_match("/.(gif)$/i", $post_image2) ) {
     // This condition is only if you wish to allow uploading of specific file types    
    $post_image2 = 'resized_'.$post_image2 ;
     move_uploaded_file($image_tmp2,"images/$post_image2");
	 
	 $insert =" insert into comments (post_id,post_image,user_id,comment,author_name,date) values('$post_slug','$post_image2','$user_id2','$comment','$user_name2','$date' ) ";

$run = mysqli_query($con,$insert);
     
}




else{


if (!preg_match("/.(gif|jpg|png)$/i", $post_image2) ) {
     // This condition is only if you wish to allow uploading of specific file types    
     echo "ERROR: Your image was not .gif, .jpg, or .png.";
      // Remove the uploaded file from the PHP temp folder
     
}

 else{
 move_uploaded_file($image_tmp2,"images/$post_image2");
 
 // ---------- Include Universal Image Resizing Function --------
include_once("2ak_php_img_lib_1.0.php");
$target_file = "images/$post_image2";
$resized_file = "images/resized_$post_image2";
$wmax = 260;
$hmax = 380;
ak_img_resize($target_file, $resized_file, $wmax, $hmax, $fileExt);
// ----------- End Universal Image Resizing Function -----------
 
 
$insert =" insert into comments (post_id,post_image,user_id,comment,author_name,date) values('$post_slug','$post_image2','$user_id2','$comment','$user_name2','$date' ) ";

$run = mysqli_query($con,$insert);

}



}
	
	}
	
	
 ?>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

$(document).on("submit", "#reply", function(e){

    e.preventDefault();
    var fd = new FormData();    
    var file = $("#imgInp")[0];
    fd.append("image2", file.files[0]);
    fd.append("comment", $(this).find('input[name="comment"]').val());

    $.ajax({
        url: 'reply.php',
        type: 'POST',

        data: fd,
        processData: false,
        contentType: false,
    }).done(function (data){
         $('#fcomment-box').fadeOut('slow', function(){

        $('#comment-box').fadeIn('slow').html(data);
        });                               
    }).fail(function(){
        alert('Ajax Submit Failed ...');    
    });

});