简体   繁体   中英

Prevent redirect page in Ajax and PHP

I configure a file upload ability on my website. The program work like a charm! Though I use Ajax to handle the php response. The problem is that when I click submit it redirects me to php and don't return the echo back to my ajax. I tried e.preventDefault() and return false to Ajax but dodn't work.

Here are my files

HTML

<form style="margin-top: -20px; width: inherit; cursor: default;" name="photo" id="imageUploadForm" enctype="multipart/form-data"  method="post" action="../lib/imgUpload.php">
      <input type="file" name="image" id="ImageBrowse"  style='//visibility:hidden;'>
      <button type="submit" name="upload" id="UploadImageBtn" value="Upload">Upload</button>
</form>

JS

$(document).ready(function(e){
    //many many other functions

    $('#imageUploadForm').on('submit', function(e) {
        var formData = new FormData(this);

        $.ajax({
            type:'POST',
            url: $(this).attr('action'),
            data:formData,
            cache:false,
            contentType: false,
            processData: false,
            success:function(data){
                alert(data);

            },
            error: function(data){
                alert('bad');
            }
        });
        e.preventDefault();

    }));

    $("#ImageBrowse").on("change", function(e) {
        e.preventDefault();
        $("#imageUploadForm").submit();
    });
});

PHP

<?php
    session_start();
    $sourcePath = $_FILES['image']['tmp_name'];      
    $targetPath = "profile_avatars/".$_FILES['image']['name'];
    $res = move_uploaded_file($sourcePath,$targetPath) ; 
    if ($res) {
        echo "yes";
    }
    else {
        echo "no";
    }
?> 

Try to execute e.preventDefault() before the other lines of code, like this:

$('#imageUploadForm').on('submit', function(e) {

    e.preventDefault();

    var formData = new FormData(this);

    $.ajax({
        method:'POST',
        url: "../lib/imgUpload.php",
        data:formData,
        cache:false,
        contentType: false,
        processData: false,
        success:function(data){
            alert(data);

        },
        error: function(data){
            alert('bad');
        }
    });
});

There also was one round closing bracket too much at the end of this function.

Try to remove the action from your form element, and return false, like this:

 <form style="margin-top: -20px; width: inherit; cursor: default;" name="photo" id="imageUploadForm" enctype="multipart/form-data" onsubmit="return false;">

Remove method="POST" from the form element and add it to your ajax call.

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