简体   繁体   中英

Posting form using AJAX

can anyone please help me with sending the below form using Ajax. All I want is to send it to the trolley1.php page for processing, no call backs or anything like that. Basically replicate the form but sending it with Ajax so the page does not go to the trolley1.php page. 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

<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

$(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 uses $ to access the methods (eg $.ajax ) Thats the reason why you get undefined as error.

So you need to load the libary first at the beginning of your page (inside <head> ). Eg directly from their 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

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