I am using this code to add data to a database using ajax. Here is the html:
<form>
Product Name:</br>
<input type=text name=productName id="addProductName"></br>
Product Description:</br>
<input type=text name=productDescription id="addProductDescription"></br>
Product Quantity:</br>
<input type=number name=productQuantity id="addProductQuantity"></br>
<button id="addProduct" type=button>Add Product</button>
</form>
<div id="productAdded">test</div>
<script language="JavaScript" type="text/javascript" src="../javascript/test.js"></script>
Here is the javascript file test.js:
var xmlhttp;
function getXmlHttpRequest(){
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function addProduct(){
getXmlHttpRequest();
var productName = document.getElementById("addProductName");
var productDescription = document.getElementById("addProductDescription");
var productQuantity = document.getElementById("addProductQuantity");
var url = "insert.php?a=" + productName + "&b=" + productDescription + "&c=" + productQuantity;
xmlhttp.open("GET", url, false);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("productAdded").innerHTML = xmlhttp.responseText
}
};
}
var button;
button = document.getElementById("addProduct");
button.addEventListener("click", addProduct);
Here is the php:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "products";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$productName = $_GET['a'];
$productDescription = $_GET['b'];
$productQuantity = $_GET['c'];
$sql = "INSERT INTO Product (ProductName, ProductDescription, ProductQuantity) VALUES ('$productName','$productDescription','$productQuantity')";
$conn->exec($sql);
echo 'Product ' . $productName . ' with quantity: ' . $productQuantity . ' Added';
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
I am getting all of the results that i expect except when i look at my database table i am seeing this instead of the data that was entered into the form:
[object HTMLInputElement]
When you do getElementById an HTMLInputElement is returned. After that you need to get the value of this element:
var productName = document.getElementById("addProductName").value;
var productDescription = document.getElementById("addProductDescription").value;
var productQuantity = document.getElementById("addProductQuantity").value;
You aren't actually getting the values from the input fields, use the value property to get it.
var productName = document.getElementById("addProductName").value;
var productDescription = document.getElementById("addProductDescription").value;
var productQuantity = document.getElementById("addProductQuantity").value;
also you should encode the date incase there ar any special characters in then
var url = "insert.php?a=" + encodeURIComponent(productName) + "&b=" + encodeURIComponent(productDescription) + "&c=" + encodeURIComponent(productQuantity);
Related
My JavaScript:
//Function that gets the chat from backend
function showmessage(str) {
if (str == "") {
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("chat").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","/backend-display.php?q="+str,true);
xmlhttp.send();
}
}
//Show any messages that will pop-up
setInterval('showmessage()',400);
//Function that updates new rows
function newrows(str) {
if (str == "") {
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("test").innerHTML = this.responseText;
var elem = document.getElementById('chat');
elem.scrollTop = elem.scrollHeight;
}
};
xmlhttp.open("GET","/test2.php?success=true"+str,true);
xmlhttp.send();
}
}
//Updates new rows every x seconds
setInterval('newrows()',300);
//Backend to send a message
function loadDoc() {
var xhttp = new XMLHttpRequest();
var mes = document.getElementById("message").value;
var message = "message=" +mes;
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("input").innerHTML = this.responseText;
}
};
xhttp.open("POST", "/backend-input.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(message);
document.forms["form"].reset();
}
PHP.ini config:
Php.ini config link
Backend for inputting:
<?php include 'auth.php';?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$name = $_SESSION["name"];
$messageunfilter = $_POST["message"];
$con = mysqli_connect('localhost','root','','chat');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
if(empty($_POST["message"])){
echo "You must enter a message...";
exit();
}else{
echo "success";
}
//Checking SQL
$check = array("\\", "'");
$change = array("\\\\", "''");
$messagefilter = str_replace($check, $change, $messageunfilter);
date_default_timezone_set('Europe/London');
$current_date = date("Y-m-d H:i:s");
mysqli_select_db($con,"ajax_demo");
$sql="INSERT INTO `chat` (`id`, `username`, `message`, `date`) VALUES (NULL, '$name', '$messagefilter', '$current_date')";
$result = mysqli_query($con,$sql);
mysqli_close($con);
?>
</body>
</html>
Backend for recieving messages from DB:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<head>
<link href="style.css" rel="stylesheet">
</head>
<?php //Selects all of the logged in users messages.
$name = $_SESSION["name"];
$con = mysqli_connect('localhost','root','','chat');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM `chat` ORDER BY date";
$result = mysqli_query($con,$sql);
$numrows = mysqli_num_rows($result);
if( $numrows == "0" or !isset($_SESSION["name"])){
echo "<div class='msg'>";
echo "<div class='username_admin'>System</div>";
echo "<div class='msg_admin'>There are no messages to display...</div>";
echo "</div>";
exit();
}else{
echo "";
}
echo "<div class='msg_container'>";
while($row = mysqli_fetch_array($result)) {
$class_msg = "msg";
$class_username = "username";
$class_message = "message";
if ($row['username'] == $_SESSION['name']) {
$class_msg = "msg_user";
$class_username = "username_user";
$class_message = "message_user";
}
echo "<div class='$class_msg'>";
echo "<div class='$class_username'><span>" . $row['username'] . "</span></div>";
echo "<div class='$class_message'><span>" . $row['message'] . "</span></div>";
echo "</div>";
}
echo "</div>";
mysqli_close($con);
?>
</body>
</html>
I am aware of websockets and my code needs to be cleaned up a lot, as well as the fact that my statements are not prepared.
For some reason after this system running for 5 minutes or so, the sessions seem to get destroyed?
I have no idea why this is? Is it because I am requesting it too many times?
Even if I have just 2 users connected messaging each other it still crashes, it can crash after 60 seconds, 1 minute?
Can someone please help me figure out why this is, I would be more than grateful.
Thank you so much for even looking at this post, even that means a lot! (Sorry for the overload of code here, I just want to be sure that I am showing you everything I can!)
According to the comments at the php docs for session_start() (http://php.net/manual/en/function.session-start.php), it may be necessary to write to the session data in order to keep the session alive under some circumstances.
I would give adding $_SESSION['time'] = time(); after your session_start()s a try and see if that helps. I'm not sure what is causing the crash but I would check the apache error logs first.
I've made a script that requests information via Json. For some variables this works just fine, for others it doesn't.
When I use alert() for the variable neighbour1 it says the variable is undefined, when doing the same for the variables number and colour it works just fine.
This is the request script:
function getcolours() {
var hr = new XMLHttpRequest();
hr.open("GET", "camp_map_script.php", true);
hr.setRequestHeader("Content-type", "application/json");
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
var data = JSON.parse(hr.responseText);
for (var obj in data) {
number = data[obj].number;
colour = data[obj].colour;
neighbour1 = data[obj].n1;
alert (neighbour1);
window["colour" + number] = colour;
var x = document.getElementsByClassName(number + ' ' + colour);
x[0].style.display = "block";
}
}
}
hr.send(null);
}
This is the php part:
<?php
include_once("../php_includes/check_login_status.php");
?><?php
$number = "";
$sql = "SELECT camp_id FROM users WHERE username='$log_username'";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_row($query);
$campid = $row[0];
$sql = "SELECT players FROM campaigns WHERE id='$campid'";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_row($query);
$players = $row[0];
$number = ($players*2)-1;
$sql = "SELECT number, colour, player, n1, n2, n3, n4, n5, n6, n7, n8 FROM lands WHERE camp_id='$campid' ORDER BY number";
$query = $connect->query($sql);
$jsonData = '{';
if ($query->num_rows > 0) {
while($row = $query->fetch_assoc()) {
$jsonData .= '"obj'.$row["number"].'":{"number":"'.$row["number"].'", "colour":"'.$row["colour"].'", "player":"'.$row["player"].'", "n1":"'.$row["n1"].'"},';
}
}
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
$connect->close();
?>
Also when I check the php document the variable n1 is echoed correctly. So the error must be on the java script side or the transit.
It is probably something stupid that I'm overlooking but I just don't see it. I've copy pasted the working parts and changed them to work with other variables but it still doesn't work. :/
Here are my files:
Backend Search PHP File:
<?php
require "../sinfo.php";
function chk_phone($orig) {
return preg_replace("/[^0-9]/","",$orig);
}
$s = $_POST["s"];
$sql = "SELECT * FROM requests WHERE id LIKE '%" . $s . "%' OR " .
"lower(firstname) LIKE '%" . strtolower($s) . "%' OR " .
"lower(lastname) LIKE '%" . strtolower($s) . "%' OR " .
"dayphone LIKE '%" . strtolower($s) . "%' ORDER BY id ASC";
$result = $conn->query($sql);
$valid = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
if ($row["status"] == "Complete" && date_compare($row["timestamp"]) < 37) {
$valid[] = $row;
}
}
}
if (count($valid) > 0) {
echo "<ul>\n";
foreach ($valid as $row) {
echo "<li onclick=\"javascript: autofill('" . $row["id"] . "', '" .
$row["firstname"] . "', '" .
$row["lastname"] . "', '" .
chk_phone($row["dayphone"]) . "', '" .
chk_phone($row["evephone"]) . "', '" .
$row["email"] . "', '" .
$row["make"] . "', '" .
$row["os"] . "', '" .
htmlspecialchars($row["issue"]) . "', '" .
$row["password1"] . "', '" .
$row["password2"] .
"');\">" . $row["id"] . " - " . $row["firstname"]. " " . $row["lastname"] . "</li>\n";
}
echo "</ul>\n";
} else {
echo "-- No Results Found --";
}?>
Here is the javascript file:
function upsearch(content) {
var xmlhttp;
try{
// Opera 8.0+, Firefox, Safari
xmlhttp = new XMLHttpRequest();
}
catch (e){
// Internet Explorer Browsers
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Something went wrong.!\nError: \n" + e);
return false;
}
}
}
xmlhttp.onreadystatechange = function() {
//if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("results").innerHTML = xmlhttp.responseText;
//}
};
var params = "s=" + content;
xmlhttp.open("POST", "ajax/requestsearch.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(params);
}
function autofill(rid, fname, lname, dphone, ephone, email, make, os, issue, password1, password2) {
document.getElementById("searchrid").value = rid;
document.getElementById("searchrid").disabled = true;
document.getElementById("custinfo").style.display = "block";
document.getElementById("firstname").value = fname;
document.getElementById("firstname").disabled = true;
document.getElementById("lastname").value = lname;
document.getElementById("lastname").disabled = true;
document.getElementById("dayphone").value = dphone;
document.getElementById("evephone").value = ephone;
document.getElementById("email").value = email;
document.getElementById("equipinfo").style.display = "block";
document.getElementById("make").value = make;
document.getElementById("make").disabled = true;
document.getElementById("password1").value = password1;
document.getElementById("password2").value = password2;
document.getElementById("originalissue").style.display = "block";
document.getElementById("originalissue").innerHTML = issue;
document.getElementById("os").value = os;
}
On the main PHP page that calls the backend page, I get all the results as expected. It displays as I want and everything. My problem is that all the lines it returns, some of them don't perform the javascript "autofill" function, while others do. It's always the same ones, so it doesn't matter if the search is done in different ways. The only thing that I could think of that could cause problems was the "issue" field from my database can have html elements, but I fix that with the htmlspecialchars() function. Before I switched it to a POST method, I was using the GET method and I would pull that same page up with the same search results and look at the code, and it would all be correct, even those ones that would not perform the function. I switched it to the POST method to see if it would make a difference, but its the exact same problem. This same problem occurs in Chrome and IE. What am I doing wrong? Or what should I do differently.
I would suggest You to use jQuery.
Just use simple ajax request like:
$.ajax({
type: 'POST',
url: 'ajax/requestsearch.php',
data: 'q='+query,
success: function(data){
var r = $.parseJSON(data);
autofill(r[0].lastname,r[0].firstname, r[0].phone, etc);
}
});
and requestsearch.php
$q = $_POST['q'];
$sql="SELECT * FROM DataBase WHERE firstname LIKE '%$q%' ORDER BY firstname asc";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$data[] = $row;
}
echo json_encode($data);
I am simply trying to update an element in an array, and the information, for whatever reason, doesn't seem to be getting through. Here is the javascript that sends the data:
var xmlhttp = new XMLHttpRequest();
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// Do Nothing
}
}
xmlhttp.open("GET","updateGame.php?q=" + str + "&e=" + recordText,true);
xmlhttp.send();
Where recordText is declared elsewhere.
And this is the PHP that hopefully recieves the q and e:
<?php
$q = intval($_GET['q']);
$e = strval($_GET['e']);
$servername = "localhost";
$username = "*****";
$password = "*****";
$dbname = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE Games SET entries=$e WHERE PINs=$q";
$result = $conn->query($sql) or die($conn->error);
$conn->close();
?>
I have checked, and no information is being updated.
I fixed your Ajax file, here it is and it works fine, I also modified your PHP file to return the data just for testing purposes. Create two text files with the given names, copy-paste next codes and run from browser :
eli_davies_1.php
<html>
<head>
<script type="text/javascript">
function ajax_send ( a )
{ var ajax = false;
if ( window.XMLHttpRequest )
ajax = new XMLHttpRequest();
else if ( window.ActiveXObject )
ajax = new ActiveXObject( "Microsoft.XMLHTTP" );
if ( ajax )
{ var qq = document.getElementById( "txt_q" ).value; // DATA TO SEND.
var ee = document.getElementById( "txt_e" ).value; // DATA TO SEND.
ajax.open("GET","eli_davies_2.php?q=" + qq + "&e=" + ee ); // EXECUTE PHP.
ajax.onreadystatechange =
function ()
{ if ( ( ajax.readyState == 4 ) &&
( ( ajax.status == 0 ) ||
( ajax.status == 200 ) ) )
{ var d = document.getElementById( "div_result" );
d.innerHTML = ajax.responseText; // DISPLAY DATA RETURNED.
}
}
ajax.send( null );
}
}
</script>
</head>
<body>
<input type="text" id="txt_q" value="123" />
<br/>
<input type="text" id="txt_e" value="xyz" />
<br/>
<button onclick="ajax_send()">Send data</button>
<br/>
<div id="div_result"></div>
</body>
</html>
eli_davies_2.php
<?php
$q = intval($_GET['q']);
$e = strval($_GET['e']);
echo "Data received = >" . $q . "< and >" . $e . "<"; // DATA RETURNED (FOR TESTING ONLY).
/*
$servername = "localhost";
$username = "*****";
$password = "*****";
$dbname = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE Games SET entries=$e WHERE PINs=$q";
$result = $conn->query($sql) or die($conn->error);
$conn->close();
*/
?>
I am making a quiz website ,on click it get questions and options from database
in a row.I want to display question in one div and options in other 3 divs.
i have two pages for it one is careerguidance.php and one is getquestion.php.
Careerguidance.php
<head>
<script>
var str=0;
function showquestion() {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("div1").innerHTML = xmlhttp.responseText;
// document.getElementById("dop1").innerHTML = xmlhttp.responseText;
// document.getElementById("dop2").innerHTML = xmlhttp.responseText;
// document.getElementById("dop3").innerHTML = xmlhttp.responseText;
}
}
str++;
xmlhttp.open("GET","getquestion.php?idd="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<button onClick="showquestion()">Next</button>
<div class='quiz' id='div1'><h2>$question</h2></div>
<div class='quizoption' id='dop1' onClick=''><h4></h4></div>
<div class='quizoption' id='dop2' onClick=''><h4></h4></div>
<div class='quizoption' id='dop3' onClick=''><h4></h4></div>
</body>
getquestion.php
<?php
$idd = intval($_GET['idd']);
require_once('db_con.php');
//$sq="select id from questions";
//$q_id = (isset($_GET['id']) ? intval($_GET['id']) : 1);
//static $r=1;
//static $q_id=0;
//$q_id++;
$sql="SELECT * FROM questions where id= '".$idd."'";
//$sql="SELECT * FROM questions WHERE id =$r";
$result = mysql_query($sql);
/*
echo "<table>
<tr>
<th>Question</th>
<th>Option1</th>
<th>Option2</th>
<th>Option3</th>
<th>Next</th>
</tr>";
*/
while($row = mysql_fetch_array($result)) {
// echo "<tr>";
echo "<h2>";
echo $row['question'];
echo "</h2>" ;
// echo "<br>" . $row['option1'] ;
// echo "<td>" . $row['option2'] . "</td>";
// echo "<td colspan='2'>" . $row['option3'] . "</td>";
// echo "</tr>";
}
//echo "</table>";
mysql_close($conn);
?>
</body>
</html>
You need to parse your response in parts and then assign values to specific divs. E.g. if your xmlhttp.responseText` looks like this:
{
"question": "Who is it?",
"answers": ["Merry", "Billy", "Joe"]
}
you will something like this:
function buildQuestionaree(data) {
//
// if data is a string
// data = JSON.parse(data);
//
var question = data.question;
var answers = data.answers;
document.getElementById("div1").innerHTML = question;
document.getElementById("dop1").innerHTML = answers[0];
document.getElementById("dop2").innerHTML = answers[1];
document.getElementById("dop3").innerHTML = answers[2];
}