简体   繁体   English

使用AJAX发布表单

[英]Posting form using AJAX

can anyone please help me with sending the below form using Ajax. 谁能帮我使用Ajax发送以下表格吗? All I want is to send it to the trolley1.php page for processing, no call backs or anything like that. 我想要的只是将其发送到traffic1.php页面进行处理,没有回电或类似的东西。 Basically replicate the form but sending it with Ajax so the page does not go to the trolley1.php page. 基本上复制表单,但是使用Ajax发送该表单,因此该页面不会转到手推车1.php页面。 I have tried so many methods but have not been able to do this. 我尝试了很多方法,但未能做到这一点。 Bill Gates or Steve Wozniak if you guys are reading this, please help 比尔·盖茨或史蒂夫·沃兹尼亚克如果您正在阅读此书,请帮助

This gives me a console $.Ajax is not a function in the console 这给了我一个控制台$ .Ajax不是控制台中的函数

<script>
$(document).ready(function(){
$('form').submit(function(event){
event.preventDefault();

var form_data = $(this).serialize();   
$.ajax({ 
    url: "trolley1.php",
    type: "POST",
    dataType:"json", 
    data: form_data
}).done(function(data){ 
    alert("Item added to Cart!"); 
    }
});
});
</script>

<?php
echo "
<div class='col-sm-3 mt-5'>
<form class='ajax' method='post' action='trolley1.php?action=add&id=$id'>
  <div class='products'>
      <a>$img</a>
      <input type='hidden' name='id' value='$id'/>
      <input type='hidden' name='name' value='$product'/>
      <input type='hidden' name='price' value='$price'/>
      <input type='text' name='quantity' class='form-control' value='1'/>
      <input type='submit' name='submit' style='margin-top:5px;' class='btn btn-info'
             value='Add to Cart'/>      
  </div>
</form>

You have one syntax error in your JS Code - see correct code 您的JS代码中有一个语法错误-查看正确的代码

$(document).ready(function(){
    $('form').submit(function(event){
        event.preventDefault();

        var form_data = $(this).serialize();   
        $.ajax({ 
            url: "trolley1.php",
            type: "POST",
            dataType:"json", 
            data: form_data
        }).done(function(data){ 
            alert("Item added to Cart!"); 
        });
    });
});

And you are using jQuery as additional javascript libary. 而且您正在使用jQuery作为其他javascript库。 jQuery uses $ to access the methods (eg $.ajax ) Thats the reason why you get undefined as error. jQuery使用$来访问方法(例如$.ajax ),这就是为什么未定义为错误的原因。

So you need to load the libary first at the beginning of your page (inside <head> ). 因此,您需要首先在页面开头(在<head>内部)加载库。 Eg directly from their CDN 例如直接从他们的CDN

<script src="https://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous"></script>

Then it should work for you 那它应该对你有用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM