dongshen4129 2015-10-08 16:36
浏览 49

通过JS使用Ajax php文件提交表单

I am trying to submit a normal html form to a database:

<form method="post" action="#" id="productForm" onsubmit="return submitProduct(this);">

With the above line I call the method "submitProduct". The code for this method is:

function submitProduct(form_ele) {
  var values = $(form_ele).serialize();
  $.ajax({
        url: "forms/ajax/admin/form_modifications.php",
        type: "post",
        data: values,
        success: function (response) {
            alert("Success");
        },
    });
} 

So with the above code I should be able to go in "form_modifications.php" script right? I haven't managed to get the "data: values" from the form yet (which it should be fine once I figure out how to go there)

In form_modifications.php I have the following (I wanted just to test it):

chdir(dirname(__FILE__)."/../../..");
require_once("config/config.inc.php");
require_once("init.php");

$sql_test = "INSERT INTO ps_test_product (name) VALUES ('test');";
Db::getInstance()->query($sql_test);

I can't understand why but it doesn't work. The query is not executed and I can't find what I am doing wrong. Can anyone help me with this?

  • 写回答

1条回答 默认 最新

  • donglu5047 2015-10-08 17:16
    关注

    I am suspecting it could be that the ajax is not fired since you have said that the direct access to form_modification.php is working fine. So I can only advise you on what you should do to debug. From there you will get more clues.

    Step 1: Dun use html inline onsubmit, so remove that code

    <form method="post" action="#" id="productForm">
     ...............
    </form>
    

    Step 2: Change Javascript code and bind submit event using jquery

        $( "#productForm" ).submit(function( event ) {
          console.log("I am running");
           var values = $(this).serialize();
           $.ajax({
                 url: "forms/ajax/admin/form_modifications.php",
                 type: "post",
                 data: values,
                 success: function (response) {
                      alert("Success");
                 },
            });
        });
    

    Step 3: Use google chrome and click inspect element and click network tab. Now click the form submit at browser by filling in whatever inputs and see if the post request is being pushed.

    Step 4: Click console tab at the inspect element and see if "I am running" is being printed out. If it does, the submit event is working.

    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程