XMLHttpRequest not showing anything - javascript

I am using XMLHttpRequest like this:
I created one variable uname for storing username and one variable msg for storing messages.
<script>
function submitChat() {
if(form1.uname.value == '' || form1.msg.value == ''){
alert('ALL FIELDS ARE MANDATORY');
return;
}
var uname = form1.uname.value;
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open('GET', 'insert.php?uname='+uname+'&msg='+msg, true);
xmlhttp.send();
}
</script>
My form looks like this
<form name="form1">
Enter your chat name: <input type="text" name="uname" /> <br />
Your message: <br />
<textarea name="msg"></textarea> <br />
Send <br/><br/>
<div id="chatlogs">
LOADING CHAT LOGS PLEASE WAIT...
</div>
what I am doing is that, when I am feeding data to the boxes(input and textarea) and then clicking the link(Send), then the chat logs should be displayed in the div section with id chatlogs, but its not happening, I created database like this:
<?php
$uname = $_REQUEST['uname'];
$msg = $_REQUEST['msg'];
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con, 'chatbox');
mysqli_query($con, "INSERT INTO logs ('username', 'msg') VALUES ('$uname', '$msg')");
$result1 = mysqli_query($con, "SELECT * FROM logs ORDER by id DESC");
while ($extract = mysqli_fetch_array($result1)){
echo "<span class='uname'>" . $extract['username'] . "</span>: <span class='msg'>".$extract ['msg'] ." </span><br />";
}
?>
and logs look like this
<?php
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db('chatbox', $con);
$result1 = mysqli_query("SELECT * FROM logs ORDER by id DESC");
while($extract = mysqli_fetch_array($result1)){
echo "<span class='uname'>" . $extract['username'] . "</span>: <span class='msg'>" . $extract['msg'] . "</span><br />";
}
?>
Right now when I am filling the input and text area and then clicking the send link, nothing is happening. Neither the data is stored in database nor it is being displayed in the div section.
Thanks for your help in advance.

Related

Creating a PHP session variable after successful AJAX call

I am having problems creating a PHP session following a successful AJAX call. Here is the AJAX code:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var em = profile.getEmail();
var name = profile.getName();
var pic = profile.getImageUrl();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('confirm-login').style.display = 'block';
}
};
xhttp.open("GET", "./assets/inc/profile.php?id="+id+"&e="+em+"&n="+name+"&p="+pic, true);
xhttp.send();
}
This part works perfectly. I only include it for completeness sake.
Here's the contents of profile.php
<?php
$id = $_GET["id"];
$email = $_GET["e"];
$name = $_GET["n"];
$pic = $_GET["p"];
require_once("db.php");
$result = $mysqli->query("SELECT googleid FROM user_tbl WHERE googleid = '$id' LIMIT 1");
if($result->num_rows == 0) {
$sql = "INSERT INTO user_tbl (googleid, email, fullname, pic, loc) VALUES ('$id', '$email', '$name', '$pic', '')";
if (mysqli_query($mysqli, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}
} else {
echo "already exists";
}
$mysqli->close();
session_start();
$_SESSION['gid'] = $id;
?>
All of this code works except for session_start(); and $_SESSION['gid'] = $id; when I return to another PHP page (which correctly has session_start(); at the very top of the page) the variable has not been created in profile.php
Any help as to what I'm doing wrong would be much appreicated.
You can't start a session after the script has sent output. (There should have been output to that effect; if there wasn't, try changing PHP's warnings.) The session_start() call must come before any echo call that is actually executed.
On an unrelated topic, you will want to learn how to escape your database parameters.

Choosing a district by city problem with php

I try to make when you select the city, show the district of this city. I am adding my code to below. I made it on local and it has not any issue but whenever I add this on online it's show noting. It consists of 3 parts; First part is input area, second part is Javascript area and last part for connect to database and get date.
here's input area:
<form action="#institutions" method="post">
<p>Select City*</p>
<select class="institutionsSelect" name="cityinstitutions" id="orders-institutions" onchange="getDetaiinstitutions(this.value);">
</select>
<p>Select District </p>
<select class="institutionsSelect" name="districtinstitutions" id="order-details-institutions">
</select> <br>
<input type="submit" name="institutionsList" autocomplete="off" value="LİST OF INSTITUTIONS" class="btn btn-md btn-blue black-hover" >
</form>
Here's javascript area;
<script type="text/javascript">
function getOrdersinstitutions() {
var ajax = new XMLHttpRequest();
ajax.open("GET", "get-orders-institutions.php", true);
ajax.send();
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var html = "<option>Select City</option>";
for (var a = 0; a < response.length; a++) {
html += "<option value='" + response[a].cityId + "'>";
html += response[a].cityName;
html += "</option>";
}
document.getElementById("orders-institutions").innerHTML = html;
}
};
}
function getDetailinstitutions(cityId) {
var ajax = new XMLHttpRequest();
ajax.open("GET", "get-order-detail-institutions.php?cityId=" + cityId, true);
ajax.send();
ajax.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(this.responseText);
var html = "<option></option>";
for (var a = 0; a < response.length; a++) {
html += "<option value='" + response[a].districtId + "'>";
html += response[a].districtName;
html += "</option>";
}
document.getElementById("order-details-institutions").innerHTML = html;
}
};
}
getOrdersinstitutions();
And here's is datebase connection areas. There are 2 different page one call get-orders-institutions.php and other is get-order-detail-institutions.php
**get-orders-institutions.php **
<?php
$connection = mysqli_connect("localhost", "userName", "password", "ys_table");
$sql = "SELECT * FROM ys_city";
$result = mysqli_query($connection, $sql);
$data = array();
while ($row = mysqli_fetch_object($result))
array_push($data, $row);
echo json_encode($data);
?>
and get-order-detail-institutions.php
<?php
$cityId = $_GET["cityId"];
$connection = mysqli_connect("localhost", "userName", "password", "ys_table");
$sql = "SELECT * FROM ys_district WHERE cityId='$cityId'";
$result = mysqli_query($connection, $sql);
$data = array();
while ($row = mysqli_fetch_object($result))
array_push($data, $row);
echo json_encode($data);
?>
Here all i used codes.
As the first option, select city should be written, but it is an empty input line. Whenever i change datebase setting i mean when i write wrong username and password Select City appear.
By the way these codes work fine in local with exactly the same codes with the same database.
Here is online page
online input area
here is local
Local input area
Local input result
What i suppose to do for take same result in online like local?
thanks in advance
UPDATE: I find what's the problem but i dont know how can i fix it.
If more than 16 rows of data are loaded into the ys_city table, it gives an error like this
How can i fix it?

Retrieving BLOB image from database using autocomplete selection

I'm trying to display a blob image stored in a database, I'm not getting any errors but the image isn't displaying, I'm just getting the default "no image" icon. Here's my code:
<script>
function showEmpimg(str) {
var xhttp;
if (str == "") {
document.getElementById("user-id").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("face").innerHTML = this.responseText;
}
};
xhttp.open("POST", "getimage.php?q="+str, true);
xhttp.send();
}
</script>
</head>
<body>
<div id="face" class="face">
</div>
<input type="text" class="form-control" id="user-id" placeholder="ID" name="emp_id" onchange="showEmpimg(this.value)" required maxlength="6" />
And the php file:
<?php
$db = mysqli_connect("localhost","root","test1","dar");
$sql = "SELECT emp_img FROM employees WHERE emp_id LIKE 'q'";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['emp_img'] ).'"/>';
?>
Any ideas?
Solved:
$db = mysqli_connect("localhost","root","test1","dar");
$sql = "SELECT * FROM employees WHERE emp_id=" . intval($_GET['q']);
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
//var_dump($result);
echo '<img class="face" src="data:image/jpeg;base64,'.base64_encode( $result['emp_img'] ).'"/>';

update php page using ajax using post requests reload the page?

I am trying to change the content of my php web page using ajax as below
the index.php page has input filed that call a function to executed on the button click but my problem is that the page is reload it
so i want to know what I am doing wrong??
Note that i am using the post requests to keep my data secure as w3schools.com recommended
inexd.php file code below
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Site Title</title>
</head>
<body align="left">
<div>
<h4 align="left">Balance Enquiry</h4>
</div>
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNumInput">
<button type="button" onclick="SendForm()">Search</button>
</div>
</form>
<script>
function SendForm()
{
alert("Hello! SendForm start");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
alert("Hello! going to send ajax");
var x = xmlhttp.open("POST","AccData.php", true);
xmlhttp.send(document.getElementById("AccNum").value); // you want to pass the Value so u need the .value at the end!!!
alert(document.getElementById("AccNum").value);
alert("Hello! SendForm end");
}
</script>
</body>
</html>
The data.php file code below
<?php
alert("Hello! php start processing");
$AccountNumber = $_POST['AccNum'];
$conn = oci_connect('admin', 'admin', 'localhost/JDT', 'AL32UTF8');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
alert("Hello! connected to oracle");
$sqlstr = 'SELECT CUSTOMER_ID,CUST_NAME,PHONE1 FROM customers where CUSTOMER_ID=:AccNum';
$stid = oci_parse($conn, $sqlstr); // creates the statement
oci_bind_by_name($stid, ':AccNum', $AccountNumber); // binds the parameter
oci_execute($stid); // executes the query
echo $AccountNumber;
/**
* THIS WHILE LOOP CREATES ALL OF YOUR HTML (its no good solution to echo data out like this)
*/
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
echo "<tr>";
foreach ($row as $item) {
echo "<td align=center>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid); // releases the statement
oci_close($conn); // closes the conneciton
?>
With the <input type="submit" value="Search"> your sending the form the "old" way to the server not with Ajax!
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNuminput">
<button type="button" onclick="sendForm()">Search</button>
</div>
</form>
<script>
function sendForm(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//Execudted when finished and everything its Okay
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("POST", "acc_data.php", true);
xmlhttp.send("accNum="+document.getElementById("AccNum").value); // you want to pass the Value so u need the .value at the end!!!
}
</script>
Then in your data.php you do not need any html you just need to process the the data that you received by the ajax post request(Session is also not needed for that) . In the xmlhttp.responseText you are receiving your answer from the server when the request is finished.
<?php
$accountNumber = $_POST['accNum'];// set a good variable name
$conn = oci_connect('admin', 'admin', 'localhost/JDT', 'AL32UTF8'); //setup connection
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR); // throws an error on connection error
}
$sqlstr = 'SELECT CUSTOMER_ID,CUST_NAME,PHONE1 FROM customers where CUSTOMER_ID=:ACCNUM'; // sql stirng
$stid = oci_parse($conn, $sqlstr); // creates the statement
oci_bind_by_name($stid, ':ACCNUM', $accountNumber); // binds the parameter
oci_execute($stid); // executes the query
/**
* THIS WHILE LOOP CREATES ALL OF YOUR HTML (its no good solution to echo data out like this)
*/
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
echo "<tr>";
foreach ($row as $item) {
echo "<td align=center>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid); // releases the statement
oci_close($conn); // closes the conneciton
?>

Creating update user profile page using PHP MySql

I have managed to go ahead with my user update page and it all seems to be fine at the form I had it reading the current details from logged in user when i clicked submit it says submit successful, then I am stuck with this page can't go back, I don't know if it worked and cannot see any error messages or any that i can see.
I am very new to coding so sorry if any silly mistake i missed out on... someone help me please....
Here is my PHP
<?php
include_once("php_includes/check_login_status.php");
session_start();
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
}
else {
echo "You have not signed in";
}
// Initialize any variables that the page might echo
$firstname = "";
$surname = "";
$u = "";
$weight = "";
$height = "";
// Make sure the _GET username is set, and sanitize it
if(isset($_GET["u"])){
$u = preg_replace('#[^a-z0-9]#i', '', $_GET['u']);
} else {
header("location: index.php");
exit();
}
// Select the member from the users database table
$sql = "SELECT * FROM users WHERE username='$u' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// check if the user exists in the database
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "That user does not exist or is not yet activated, press back";
exit();
}
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$firstname = $row["firstname"];
$surname = $row["surname"];
$weight = $row["weight"];
$height = $row["height"];
$profile_id = $row["id"];
$u = $row["u"];
}
// this is the calculation of the BMI index
//$BMI = ($weighteight / ($heighteight * $heighteight))* 10000;
if($firstname =="" || $surname == ""|| $weight == "" || $height == ""){
echo "The form submission is missing values.";
exit();
} else {
$p_hash = md5($p);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (firstname, surname, weight, height)
VALUES('$fn','$sn','$w','$h')";
$query = mysqli_query($db_conx, $sql);
$uid = mysqli_insert_id($db_conx);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
if (!file_exists("user/$u")) {
mkdir("user/$u", 0755);
}
// Email the user their activation link
$to = "$e";
$from = "k1003140#kingston.ac.uk";
$subject = 'studentnet.kingston.ac.uk/k1003140';
$message = '<!DOCTYPE html><html><head><meta charset="UTF-8"><title>yoursitename Message</title></head><body style="margin:0px; font-family:Tahoma, Geneva, sans-serif;"><div style="padding:10px; background:#333; font-size:24px; color:#CCC;"><img src="http://www.yoursitename.com/images/logo.png" width="36" height="30" alt="yoursitename" style="border:none; float:left;">yoursitename Account Activation</div><div style="padding:24px; font-size:17px;">Hello '.$u.',<br /><br />Click the link below to activate your account when ready:<br /><br />Click here to activate your account now<br /><br />Login after successful activation using your:<br />* E-mail Address: <b>'.$e.'</b></div></body></html>';
$headers = "From: $from\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\n";
mail($to, $subject, $message, $headers);
echo "signup_success";
exit();
}
exit();
?>
Here is my Javascript code
<script>
function signup(){
var u = _("username").value;
var fn = _("firstname").value;
var sn = _("surname").value;
var w = _("weight").value;
var h = _("height").value;
var e = _("email"). value;
var status = _("status");
if(fn == "" || sn == "" || w == "" || h == ""|| g == ""){
status.innerHTML = "Fill out all of the form data";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "signup.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("signupbtn").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("fn="+fn+"&sn="+sn+"&w="+w+"&h="+h+);
}
}
here i added some more of my code to see the HTML
<body>
<?php include_once("template_pageTop.php"); ?>
<div id="pageMiddle">
<form name="signupform" id="signupform" onsubmit="return false;">
<div id="usernamecss"><?php echo $u; ?></div>
<p><b>Is the viewer the page owner, logged in and verified? <?php echo $isOwner; ?></b></p>
<p>First Name: <input type="text" name="firstname" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$firstname?>'></p>
<p>Surname: <input type="text" name="surname" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$surname?>'></p>
<p>Weight: <input type="text" name="weight" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$weighteight?>'></p>
<p>Height: <input type="text" name="height" onfocus="emptyElement('status')" size="35" maxlength="15" value='<?=$heighteight?>'></p>
<button id="signupbtn" onclick="signup()">Create Account</button>
</div>
</form>
<?php include_once("template_pageBottom.php"); ?>
<span id="status"></span>
</body>
i can't write comment so i will write here
U should use session_start(); at the first line of the page and this may cause some problem try it
session_start();
include_once("php_includes/check_login_status.php");
As I can see you are doing a POST in your ajax but are reacting to GET in your php.
Try to change:
if(isset($_GET["u"])){
to:
if(isset($_POST["u"])){
or:
if(isset($_REQUEST["u"])){

Categories