I am trying to insert data from form to database without refreshing page, my HTML page looks like this:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<form name="form1" method="post" action="">Enter Name
<input type="text" name="t1" id="t1">
</td>
<br>Enter City
<input type="text" name="t2" id="t2">
</td>
<br>
<input type="button" name="button1" value="Insert to DB" onClick="aa()">
</form>
<div id="d1"></div>
<script type="text/javascript">
function aa() {
var xmlhttp = new XMLhttpRequest();
xmlhttp.open("GET", "insert.php?name=" + document.getElementById("t1").value + "&city" + document.getElementById("t2").value, false);
xmlhttp.send(null);
document.getElementById("d1").innerHTML = xmlhttp.responseText;;
}
</script>
</body>
</html>
and my insert.php looks like:
<?php
$name = $_GET["name"];
$city = $_GET["city"];
mysql_connect("localhost","root", "");
mysql_select_db("dwh");
mysql_query("insert into table1 values('$name','$city')");
echo "Record inserted";
?>
In my opinion this should send PHP all data in "get" and php should just take it and insert it. Somehow it's not. Maybe i miss something, can you help me to find a problem?
browser console say:
(index):16 Uncaught ReferenceError: XMLhttpRequest is not defined(index):16 aa(index):9 onclick
Thank you a lot.
p.s. I understand my MYSQL connect is security risk, this was created just to test how to make it work.
4 Answers 4
(index):16 Uncaught ReferenceError: XMLhttpRequest is not defined(index):16 aa(index):9 onclick
JavaScript is case sensitive. The function is XMLHttpRequest (with a capital H).
1 Comment
Try include the column names of tables, ex:
insert into table1 (column1, column2) values('$name','$city')
in addition, use another variable to check if your query execute successfully or not:
$result = mysql_query("insert into table1 (column1, column2) values('$name','$city')");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
3 Comments
You're missing an equal sign following the word "city" in &city and is required when you build the query string:
xmlhttp.open("GET", "insert.php?name=" + document.getElementById("t1").value + "&city" + document.getElementById("t2").value, false);
should be
xmlhttp.open("GET", "insert.php?name=" + document.getElementById("t1").value + "&city=" + document.getElementById("t2").value, false);
1 Comment
There are two things that you need to fix:
In line
var xmlhttp = new XMLhttpRequest();it should bevar xmlhttp = new XMLHttpRequest();with a capitalH.You need to give
idto<input>as you are appending the value bygetElementById(). Currently there are no elements for theidthat you have passed.
method="post"mysqlextension, it's depreacted, and has been for some time. Read the red warning on the man, and click the links. Learn to use (and love)PDOand/ormysqli(theiis for improved). Those are the replacement extensions