2017-07-15 01:43
浏览 176

jQuery Ajax在一个表单中形成两个提交按钮

I have 2 button in one form. When I click the first or second button, both write example an alert, but the Ajax request doesn't run. I need a form, because i would like to upload images. I don't know what is the problem.


<!DOCTYPE html>
    <meta charset="utf-8">
    <title>jQuery Ajax two submit in one form</title>
    <script src=""></script>

<form id="animal-upload" method="post" enctype="multipart/form-data">

    <input type="text" name="animalname" id="animalname">

    <input type="file" name="imagefile" id="imagefile">

    <button type="submit" name="publish" id="publish">Publish</button>
    <button type="submit" name="save" id="save">Save</button>



$(document).ready(function() {

$('#animal-upload').on('submit', function() {

    return false;


$('#publish').click(function() {



$('#save').click(function(e) {



        url: "animal-upload.php",
        type: "POST",
        data: new FormData(this),
        contentType: false,
        processData: false,
        success: function(data) {










$connect = mysqli_connect("localhost", "root", "", "test");


$status = '';

$animalname = $connect->real_escape_string($_POST["animalname"]);

if ($_FILES['imagefile']['name'] != '') {

    $extension = end(explode(".", $_FILES['imagefile']['name']));
    $allowed_type = array("jpg", "jpeg", "png");

    if (in_array($extension, $allowed_type)) {

        $new_name = rand() . "." . $extension;
        $path = "animals/" . $new_name;

        if (move_uploaded_file($_FILES['imagefile']['tmp_name'], $path)) {

            mysqli_query($connect, "INSERT INTO animals (animalname,image) VALUES ('".$animalname."','".$path."')");

            $status = 'Successful!';


    } else {

        $status = 'This is not image file!';


} else {

    $status = 'Please select image!';


echo $status;

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongtao4787 2017-07-15 02:04

    After trial and errors I found the script work if you change this line :

    data: new FormData($("#animal-upload")[0]),

    Because that selects the form object.

    You may consider some security tips :

    • Don't divulge your password in public
    • Don't let your database users connect without passwords
    • Make a user with strict minimum privileges just for the purpose to connect to your database from PHP scripts (it's called the principle of least privileges)
    • Rename your uploaded file

    For the file upload to work :

    • Make sure you have the right permissions on the directory pointed by upload_tmp_dir in php.ini file
    • You may need to check that your file size doesn't exceed the memmory_limit directive too

    good luck,

    解决 无用
    打赏 举报

相关推荐 更多相似问题