Ryan D Ryan D - 10 months ago 69
jQuery Question

Submit ajax form without page refresh php

I have this form and ajax call in my index.php-

<form method='post' id='saleForm' >
<input type='text' name='addCustomer' class='addInput' id='adlastname' placeholder='customer last name'>
<input type='text' name='addYear' class='addInput' id='adYear' placeholder='year'>
<input type='text' name='addMake' class='addInput' id='adMake' placeholder='make'>
<input type='text' name='addModel' class='addInput' id='adModel' placeholder='model'>
<input type='text' name='addGross' class='addInput' id='adGross' placeholder='front gross'>
<input type='hidden' name='Id' value='<?php echo $id;?>'>
<input type='submit' name='subSale' id='subSale' value='Save' >

$("form").submit(function(e) {
var url = "add.php"; // the script where you handle the form input.

type: "POST",
url: url,
data: $("form").serialize(), // serializes the form's elements.
success: function(data)
alert(data); // show response from the php script.

e.preventDefault(); // avoid to execute the actual submit of the form.

I am trying to submit it to the DB using add.php -

$cust = $_POST['addCustomer'];
$addMake = $_POST['addMake'];
$addModel = $_POST['addModel'];
$addYear = $_POST['addYear'];
$addGross = $_POST['addGross'];
$subSale = $_POST['subSale'];
$soldDate = date('m/d/yy');

$sql = "INSERT INTO `$sold_table` ( `Id`,`Customer`, `Year`, `Make`, `Model`, `FrontGross`, `SoldDate` ) VALUES (NULL,'$cust', '$addYear', '$addMake', '$addModel', '$addGross', '$soldDate')";
if (mysqli_query($conn, $sql)) {
echo 'success!';
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);

When I click the Save button it shows the empty alert and the data isnt getting pushed for some reason.. Any idea where I am going wrong here? i know the Insert is correct as it works when I dont use the ajax call and just use the form action..

Answer Source

When using jQuery to submit the form, the submit button isn't used. Therefore it will turn up empty once PHP receives the posted data. Your script is checking $subSale to perform the query, which now fails.

Try to supply a hidden input with the name SubSale and it wil work again. Another solution is to remove this entire if statement, as per your own suggestion.