Menel Menel - 4 months ago 11
PHP Question

Form Submission Using Ajax not working

I have a problem getting my form to insert the records into the database. I just can't figure out where I'm wrong...

My form is bellow

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="script.js"></script>

<form id="form" name="form">
<div>
<label>Name :</label>
<input id="name" type="text">
<label>Email :</label>
<input id="submit" onclick="myFunction()" type="button" value="Submit">
</div>
</form>


a script script.js

function myFunction() {
var name = document.getElementById("name").value;
var dataString = 'name1=' + name;
if (name == '') {
alert("Please Fill All Fields");
} else {
$.ajax({
type: "POST",
url: "ajaxjs.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}


and a php script ajaxjs.php

<?php
include ('./includes/connection.php');
$name1 = $_POST['name1'];
if (isset($_POST['name1'])) {
$query = mysql_query("INSERT INTO db VALUES('TEST','name1')");
}
?>


developer tools show message:
script.js:5 Uncaught ReferenceError: dataString is not definedmyFunction @ script.js:5onclick @ test.html:9

Answer

Your Ajax code working well But your query command look like wrong Please try

INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);

enter image description here

Update: Source code working well

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
    function myFunction() {
        var name = document.getElementById("name").value;
        var dataString = 'name1=' + name;
        if (name == '') {
            alert("Please Fill All Fields");
        } else {
            $.ajax({
                type: "POST",
                url: "ajaxjs.php",
                data: dataString,
                cache: false,
                success: function(html) {
                alert(html);
                }
            });
        }
        return false;
    }
</script>
<form id="form" name="form">
<div>
<label>Name :</label>
<input id="name" type="text">
<label>Email :</label>
<input id="submit" onclick="myFunction()" type="button" value="Submit">
</div>
</form>

And ajaxjs.php

<?php
    // include ('./includes/connection.php');
    $name1 = $_POST['name1'];
    echo $name1;
    // if (isset($_POST['name1'])) {
    // $query = mysql_query("INSERT INTO db VALUES('TEST','name1')");
    // }
?>