提交带有ajax响应的按钮而不是更改页面

时间:2014-04-11 01:35:07

标签: javascript php jquery ajax

我有一个表单,当前按下提交按钮后,它会更改网站以回显成功消息。我想当用户点击提交按钮时,一条消息将显示他已成功添加记录,而不更改页面。我认为正确的方法是ajax。 打开任何建议

下面是用于将值插入数据库的表单和php文件

形式

<div id="addForm">
     <div id="formHeading"><h2>Add Product</h2></div><p>

    <form id = "additems" action="../cms/insert.php" enctype="multipart/form-data" method="post"/>
      <label for="title">Title: </label><input type="text" name="title"/>
      <label for="description">Desc: </label><input type="text" name="description"/>
      <label for="price">Price: </label><input type="text" name="price" />
      <label for="stock">Quan: </label><input type="text" name="stock" />
      <p>     

<small>Upload your image <input type="file" name="photoimg" id="photoimg" /></small>

<div id='preview'>
</div>

     <select name="categories">
              <option value="mens">Mens</option>
              <option value="baby_books">Baby Books</option>
              <option value="comics">Comics</option>
              <option value="cooking">Cooking</option>
              <option value="games">Games</option>
              <option value="garden">Garden</option>
              <option value="infants">Infants</option>
              <option value="kids">Kids</option>
              <option value="moviestv">Movies-TV</option>
              <option value="music">Music</option>
              <option value="women">Women</option>
    </select>           
           <input type="submit" id="submit_form" name="Submit" value="Add new item">
          </form>

insert.php(在表单中使用)

session_start();
$session_id='1'; //$session id
$path = "../cms/uploads/";

    $valid_formats = array("jpg", "png", "gif", "bmp");
    if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
        {
            $name = $_FILES['photoimg']['name'];
            $size = $_FILES['photoimg']['size'];

            if(strlen($name))
                {
                    list($txt, $ext) = explode(".", $name);
                    if(in_array($ext,$valid_formats))
                    {
                    if($size<(1024*1024))
                        {
                            $actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
                            $tmp = $_FILES['photoimg']['tmp_name'];
                            if(move_uploaded_file($tmp, $path.$actual_image_name))
                                {

$table = $_POST['categories'];
$title = $_POST['title'];
$des = $_POST['description'];
$price = $_POST['price'];
$stock = $_POST['stock'];
    $sql="INSERT INTO $table (title, description, price, image, stock)
    VALUES
    ('$title','$des','$price','$path$actual_image_name','$stock')";

    if (!mysqli_query($con,$sql))
    {
        die('Error: ' . mysqli_error($con));
    }
    die("1 record added into the $table table");


        }
        else
            echo "failed";
        }
        else
            echo "Image file size max 1 MB";                    
        }
        else
            echo "Invalid file format..";   
        }

        else
            echo "Please select image..!";

        exit;
    }

我有这个脚本,但我无法让它工作

<script>
$(document).ready(function () {
    $('input#submit_form').on('click', function() {
        $.ajax({
            url: '../insert.php',// TARGET PHP SCRIPT
            type: 'post',   // HTTP METHOD
            data: {
                'title' : $('input[name="title"]').val()
            },
            success: function(data){
                alert(data); // WILL SHOW THE MESSAGE THAT YOU SHOWED IN YOUR PHP SCRIPT.
            }
        });
    });
})

</script>

1 个答案:

答案 0 :(得分:1)

你的代码很好。 AJAX调用可能正在发生,但您还没有告诉他按钮停止其默认行为(导航)。这是需要改变的。请注意,我已在您的回调中添加了event参数。

$('input#submit_form').on('click', function(event) {
    event.preventDefault(); //Don't do your default behavior, button
    $.ajax({
        url: '../insert.php',
        type: 'post',
        data: {
            'title' : $('input[name="title"]').val()
        },
        success: function(data){
            alert(data);
        },
        //if it breaks, you want to be able to press F12 to see why
        error: function(data){
            window.console.log(data);
        }
    });
    return false;
});

即使这不起作用并且您的代码还有其他问题,您至少可以在提交表单后按F12查看是否还有其他错误(来自您的php的错误,404来自错误链接的错误等)。当你立即被引导到提交页面时,看到你做错了什么并不容易。