Search code examples
ajaxformsajaxform

How do you post a form with ajax in php?


I'm trying to use ajax to submit a form but I set it when it's successful a jquery alert should show but it's not showing so I think it's unsuccessful. Do you guys know why??

this is the form I'm trying to submit with ajax

<b>Product Title: </b><br><input style="width: 50%;" class="form-control itemtitle" type="text" name="title" required="true"><br>
<b>Product Description: </b><br><input style="width: 50%;" class="form-control itemdescription" type="text" name="description" required="true"><br>
<b>Product Price: </b><br><input style="width: 50%;" class="form-control itemprice" type="number" name="price" required="true"><br>
<b>Product Image Address: </b><br><input style="width: 50%;" class="form-control itemimageaddress" type="text" name="image" required="true"><br>
<button type="submit" class="btn btn-primary createproductsubmit">Create Product</button>

this is the ajax I'm using

$(".createproductsubmit").click(function(){
    var itemtitle = $(".itemtitle").val();
    var itemdescription = $(".itemdescription").val();
    var itemprice = $(".itemprice").val();
    var itemimageaddress = $(".itemimageaddress").val();

    var dataString = "itemtitle=" + itemtitle + "&itemdescription=" + itemdescription + "&itemprice=" + itemprice + "&itemimageaddress=" + itemimageaddress;

    $.ajax({
        type: "POST",
        url: "pages/newproductaction.php",
        data: dataString,
        cache: false,
        success: function(result)
        {
            alert(result);
        }
    });
});

Solution

  • Just simply use

    $.post("pages/newproductaction.php", {
    itemtitle: itemtitle,
    itemdescription: itemdescription,
    itemprice: itemprice,
    itemimageaddress: itemimageaddress
    }, function(data){
    
    });