0

I am making a page on a website in PHP where a user fills out 3 fields and hits submit. The submit button should call my AJAX function to send the data to a database connection PHP file. I can confirm the data is sent from AJAX (via an alert) and the function returns a Success. This must mean my database query file is not interpreting the data correctly. Please help me understand where I went wrong.

Code from php page where the form is:

<script type="text/javascript">
function storeInvoice() {
    //var c_name = document.getElementById('c_name');
    //var c_license = document.getElementById('c_license');                         
    //var c_licenseemail = document.getElementById('c_licenseemail');
    var data=$('#myForm').serialize();
        $.ajax({
        url: "/paydb.php",
        type: "POST",
        data: data,
        async:false,
        dataType:'html',
        success: function (value) {
            alert("Sent: "+data);
        }
    });
}
</script>

Relevant Code from Database php file:

mysqli_select_db($conn, "main_db" );

$c_license = $_POST['c_license'];
$c_name = $_POST['c_name'];
$c_licenseemail = $_POST['c_licenseemail'];

//Another method was attempted below.
//$data=$_POST['serialize'];
//$c_licenseemail = $data['c_licenseemail'];
//$c_license = $data['c_license'];
//$c_name = $data['c_name'];

$query = "INSERT INTO `invoices`(`company`, `licensenum`, `licenseemail`) VALUES ('$c_name','$c_license','$c_licenseemail');";
mysqli_query($conn, $query);

The data is sent as:

c_name=testname&c_license=3&c_licenseemail=testemail%40email.com

Any help is much appreciated!

11

2 Answers 2

4

Please use the

mysqli_query($conn, $query) or die(mysqli_error($conn));

For duplicate key, you need to make the primary key to auto increment in your database.

Sign up to request clarification or add additional context in comments.

2 Comments

Very helpful, thank you. Seems to be working as intended now.
Glad, i could help.
1

In your success callback function replace alert(data) with alert(value) and in your database.php file echo any of the post variables to just check whether the values are correctly sent to database.php via ajax post.

3 Comments

Please, quit using alert() for troubleshooting., use console.log() instead.
The echos have the correct value. For example echo "c_license" sends back 3 if 3 was typed into that field.
It's wierd, it sent the query to the DB after making these small changes only. But it only worked twice and now no longer works. I'm confused..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.