JS bug: input field repeated with xmlhttp response text - javascript

This is a follow up of another question I asked last night. My problem now is not that the script doesn't works, but that I'm getting some very strange repeat of an HTML input element when my xmlhttprequest object returns the response text. Here's the code:
<!DOCTYPE HTML>
<?php
if(!empty($_GET['uName']))
{
$r = mysql_connect("localhost", "root", "pass") or die("Couldn't connect to db");
mysql_select_db("db", $r) or die ("Couldn't select db");
$q = mysql_query("select * from users where uName = '{$_GET['uName']}'") or die("Couldn't query table");
$data = mysql_fetch_assoc($q);
mysql_close($r);
}
?>
<html>
<head>
</head>
<body>
<form>
<input type="text" name="fUName" onchange="ShowUser(fUName.value);" value="name" style="width:125px;">
</form>
<div id="display"><?php print "ID = {$data['id']}"; ?></div>
</body>
</html>
<script type='text/javascript'>
function ShowUser(name)
{
if(name.length == 0)
{
document.getElementById("display").innerHTML = "Please enter a username to check";
return;
}
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("display").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "index.php?uName=" + name, true);
xmlhttp.send();
}
</script>
Here's the strange problem:
There should only be one input field, and is orginally, however when I enter text into it and it loses focus, the JS is triggered and also prints out another input field.
Please ignore the bad practice of PHP, JS and HTML/CSS in one script, this was supposed to be a quick test that has turned for the worse :)
I'm baffled!
Thanks for any help.

The problem lies in the fact that all of your code is in one page. Consider this: you load up index.php. After it's all displaying then you call this same page again (for your AJAX request) so you're essentially saying "Hey, I want you to try and load this page again," hence why you're ending up with duplicate fields.
Try separating out your files in to something like index.php and getuser.php or something of the sort.

Related

JSON echo opening new tab

I'm having a really odd problem and iv'e been going at it for a while now, scouring the internet for answers and not finding any. I'm trying to parse a JSON object (which has been successful so far) but the problem I have is that when I link to my HTML file it opens a new tab after clicking submit on the HTML form part. Im sure that this is a stupid question but i really haven't found an answer to it. I'm using PHP to encode a simple JSON object. Here is my code for the HTML part:
<!DOCTYPE HTML>
<HTML>
<body>
<center>
<H1> Registration </H1>
<form action = "/Register.php" method = "post">
<h2>Username:</h2>
<input type = "text" name = "username"><br>
<h2>Name:</h2>
<input type = "text" name = "name"><br>
<h2>Password:</h2>
<input type = "password" name = "password"><br>
<h2>Age:</h2>
<input type = "number" name = "age"><br><br>
<input type = "submit" name = "Submit">
</form><br>
Back To Login
<p id = "demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.success;
}
};
xmlhttp.open("GET", "Register.php", true);
xmlhttp.send();
</script>
</center>
</body>
</HTML>
And here is the code for the php/json part:
<?php
$con = mysqli_connect("localhost", "id5137223_bellevueeast", "BEAST", "id5137223_users");
$name = $_POST["name"];
$age = $_POST["age"];
$username = $_POST["username"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO Users (name, username, age, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "ssis", $name, $username, $age, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);
?>
It's opening a new window/tab because you are not preventing the default behavior of the HTML form, which will submit to it's own location. Basically it sends a request to the page the form is on with the get/post data from the form attached. Your JavaScript function executes fine, but then the default action of the form causes a second window to open.
If you do not want this to happen, you have to break or stop the default behavior of the HTML form with prevent default.
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Judging from your code, I am guessing that you want to call a JSON from Register.php and display it on the same page. In this case, what you need to do is to encase you XMLRequest in a Javascript function like so
function showResult() {
//do your XMLRequest stuff here
//change the div accordingly
document.getElementById("placeholder").innerHTML=*prettified json here*;
}
Then what you need to do is create a div to show your results and act as a placeholder
<div id="placeholder">
Next up is to change the submit into a button and add onPress="showResult()" to it.
<button onPress="showResult()">
You don't need submit if you are using AJAX
WOW. I realized that I am, in fact, an idiot. I was diagnosing the problem completely wrong. I thought that the form was acting up when in fact it was doing exactly what it was supposed to: Showing the data in the tab after the form went through. I finally got to do what I wanted it to though by doing this:
<iframe id="invisible" name="invisible" style="display:none;"></iframe>
and then I made the form target the iframe so it would not display anything
-_- sorry for troubling you all.

how to write php inside javascript

I write php inside JavaScript in the following way. even though the delete function is working that alert doesn't come.
Here is my code:
Delete.php
<script type="text/javascript">
function delete_id(id) {
if (confirm('Are you sure To Remove This Record ?')) {
<?php
include('database_connect.php');
if (isset($_GET['variable'])) {
$sql_query = "DELETE FROM register WHERE id=".$_GET['variable'];
mysqli_query($con, $sql_query);
header("Location: newusers.php");
}
mysqli_close($con);
?>
}
}
</script>
You can't do it like this. The correct way would be to make an ajax request to backend, and then have php delete the row.
Edit
here is some sample code for you
<script>
function delete_id() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert("deleted");
}
};
xhttp.open("GET", "/delete.php", true);
xhttp.send();
}
</script>
and the delete.php goes like
<?php
//write code for delete here
?>
Another point is that header("Location...") would redirect but in ajax, hence it is better to not use php redirect, but check in javascript and then use document.location for the redirect.

Error when trying to call javascript function

I'm trying to add a listener into the 'Yes' button which is shown in the code below.I want this function to save this boolean value into approval field in my database like:$query_row['approval']==1; and a message to display on it.But when executing the code nothing happens after clicking on the'Yes button'.
Can someone please show me how to fix this code if there is an error on it?
Thanks in advance!
This is my code:
<html >
<head>
<title></title>
</head>
<body>
<?php
if( !($database=mysql_connect("localhost","root",""))||!(mysql_select_db("st_login",$database)) )
print("Could not connect");
$result = mysql_query("SELECT * FROM `login` WHERE `admin` = 0 AND `approval`=0");
// if($_POST['admin']==0) {//perjashton administratorin
if(mysql_num_rows($result) == 0) {//esht aprovuar llogaria
if(!($result=mysql_query($query,$database)))
{
print("Could not execute query");
die (mysql_error());//ose error
}
//nese esht aprovuar logini i st.
echo "You are approved";
}
else //approval=0
echo"YOU HAVE NEW REQUESTS WAITING FOR APPROVAL IN YOUR WEBSITE!!!<br />";
while($query_row=mysql_fetch_assoc($result)){
$firstname=$query_row['firstname'];
$lastname=$query_row['lastname'];
$username=$query_row['username'];
$password=$query_row['password'];
$email=$query_row['email'];
$cv=$query_row['cv'];
echo $firstname.' '.$lastname.' has this cv:'.$cv.'<br /> Do you want to approve his account?
<button id="but">Yes</button><button>No</button><br />
<p id="demo"></p>';
?>
<script>
document.getElementById("but").addEventListener("click", MyFunction());
function MyFunction() {
$query_row['approval']==1;
document.getElementById("demo").innerHTML = "This account is approved";}
</script>
<?php
}mysql_close($database);
?>
</body>
</html>
And this is my database with the approval field which boolean value I'm trying to change:
Change document...addEventListener("click", MyFunction()); to document...addEventListener("click", MyFunction); otherwise your function executes immediately and only once.
You can't modify a value in the database only with changing value of the output array. You have to create a new php file and call it asynchronuslly. Read more about updating values in the database here and about calling files asynchronuslly here.
First, I will edit your main file because it's a mess (sorry to say that, but don't worry, it was same with me):
<html>
<head>
<title></title>
<script>
function MyFunction(id) {
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
if(xhttp.responseText.indexOf("UPDATE WENT OK")!=-1)
document.getElementById(id).nextSibling.innerHTML = "This account is approved";
}
else {
document.getElementById(id).nextSibling.innerHTML = "An error occured while approving this account";
}
}
xhttp.open("GET", "ajax_file.php?id="+id, true);
xhttp.send();
}
</script>
</head>
<body>
<?php
if(!($database = mysql_connect("localhost","root","")) || !(mysql_select_db("st_login",$database)))
print("Could not connect");
else {
$result = mysql_query($database,"SELECT * FROM `login` WHERE `admin` = 0 AND `approval`=0");
if(!$result){
print("Could not execute query");
die (mysql_error());//ose error
}
else{
if(mysql_num_rows($result) == 0) {//esht aprovuar llogaria
//nese esht aprovuar logini i st.
echo "You are approved";
}
else { //approval=0
echo"YOU HAVE NEW REQUESTS WAITING FOR APPROVAL IN YOUR WEBSITE!!!<br/>";
while($query_row=mysql_fetch_assoc($result)){
$firstname=$query_row['firstname'];
$lastname=$query_row['lastname'];
$username=$query_row['username'];
$password=$query_row['password'];
$email=$query_row['email'];
$cv=$query_row['cv'];
echo $firstname.' '.$lastname.' has this cv:'.$cv.'<br /> Do you want to approve his account?';
?><div class="container"><button id="<?php echo $query_row['id'];?>" onclick="MyFunction(this.id)">Yes</button><button>No</button><br />
<p class="demo"></p></div><?php
}
}
}
}
mysql_close($database);
?>
</body>
</html>
Now, create a php file named ajax_file.php (in the same folder):
<?php
if(!($database = mysql_connect("localhost","root","")) || !(mysql_select_db("st_login",$database)))
die("Could not connect");
else {
$id = intval($_GET['id']);
$result = mysql_query($database,"UPDATE table `login` SET approval = 1 WHERE `id` = '".$id."'");
if(!$result){
print("Could not execute query");
die (mysql_error());//ose error
}
else{
echo "UPDATE WENT OK";
}
Do not hesitate to ask me about any detail how this works. Also, this might not be correct because i don't exactly know what you are doing or want to do with the file you provided. But, if you'll give me the details, I will edit it so it will work.

AJAX call to php not working

I'm working on AJAX programming in which I have a little problem. In the below code, I think my php script is not echoing back success. I'm trying to insert values into my database table. Accordingly, the values are getting inserted into the table. I have a span element on my page which by default shows nothing. But if the php script is echoing back success, it must show "AJAX worked". If my PHP script is not echoing back "success", it must show "AJAX didn't work". But it is showing "AJAX didn't work" though the values are getting inserted. If I didn't include the database code, then my script is echoing back success and the span element is showing "AJAX worked". But if I include database code, I think it is not echoing back success and the span elemnt is showing "AJAX didn't work". Below is my code:
<head>
<meta charset="UTF-8">
<title></title>
<script src="js/main.js"></script>
<script src="js/ajax.js"></script>
<script>
function insert(){
var elem = _("myTextArea").value;
var result = _("result");
result.innerHTML += elem + "<br>";
elem.value = "";
var ajax = ajaxObj("POST", "dynamicdiv_parser.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == "success"){
_("status").innerHTML == "AJAX worked";
}
else{
_("status").innerHTML == "AJAX didn't work";
}
}
}
ajax.send("post="+elem+"&type=a");
}
</script>
</head>
<body>
<form name="dynamicdivform" id="dynamicdivform" onsubmit="return false;">
<p id="result"></p>
<textarea name="myTextArea" id="myTextArea" cols="100" rows="14"></textarea><br>
<input type="button" id="postBtn" value="POST" onClick="insert()">
<span id="status"></span>
</form>
</body>
I have included two JavaScript files in my program which are main.js and ajax.js. Below is their code.
This is main.js:
function _(x){
return document.getElementById(x);
}
This is ajax.js:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
This is my PHP script which is echoing back success
<?php
if(isset($_POST["post"])){
include_once("php_includes/dbconsampledb.php");
$data = $_POST['post'];
$type = $_POST['type'];
$sql = "INSERT INTO posts(data, type)
VALUES('$data','$type')";
$query = mysqli_query($db_conx, $sql);
echo "success";
}
?>
Before posting this question, I have tried the works but I didn't find any solution. This is very important to me. So please can anyone debug it and tell me what the problem is... Thanks in advance!!
_("status").innerHTML == "AJAX worked";
should be
_("status").innerHTML = "AJAX worked";
with one = only
My suggestion is to use a console.log() for debuging your ajax response.
if(ajaxReturn(ajax) == true) {
console.log('Response: ', ajax.responseText);
if(ajax.responseText == "success"){
Probably there is some errors with DB functionality.

AJAX chat system not working

I can't seem to work this one out. Been a few days and still no progress after re-writing it more times than I can count on my hands.
Here is the Javascript (On same page as html)
Summary: User types text into the input box. That gets sent off to be processed, which then gets sent back and displayed on the screen in the box ID'd as DisplayText on the html page.
<script type="text/javascript">
function SendText() {
if (document.getElementById("Text").innerHTML == "") {
return;
} else
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("DisplayText").innerHTML = xmlhttp.responseText;
}
}
Text = document.getElementById("Text").value;
xmlhttp.open("GET", "php/Test.php?Chat=" + Text, true);
xmlhttp.send();
}
}
</script>
Here is the HTML (Same page as the script)
<div>
<p>
<span id="DisplayText">
TEXT GOES HERE
</span>
</p>
</div>
<form action="" onsubmit="SendText();">
<input type="" name="" id="Text" />
<input type="submit" value="Send" name="Send" />
</form>
The PHP code is here
<?php
session_start();
include ("Connect.php");
$Connection = mysqli_connect("localhost", "root", "", "chatsystem");
$Create = "CREATE TABLE " . $_SESSION["Username"] . "Chat(Username VARCHAR(255), Chat VARCHAR(255))";
////////////////////////////////////////////////////////////////////////////////
$DatabaseExist = $Connection->query("SELECT 1 FROM " . $_SESSION["Username"] . "Chat");
if ($DatabaseExist !== false) {
echo "Database exists";
doSomething();
} else {
echo "Database does not exist";
mysqli_query($Connection, $Create);
doSomething();
}
////////////////////////////////////////////////////////////////////////////////
function doSomething() {
// Get the sent chat
$Input = $_REQUEST["Chat"];
// Insert into the database the new chat sent
mysqli_query($Connection, "INSERT INTO " . $_SESSION["Username"] . "chat (`Username`, `Chat`) VALUES ('$_SESSION[Username], '$Input')");
// Select everything from the database
$Result = $Connection->query("SELECT * FROM " . $_SESSION["Username"] . "Chat");
// Display everything from the database in an orderly fashion
// --
// For the length of the database
// Append to a variable the next table row
// --
while ($Row = $Result->fetch_array()) {
// Make Variable accessable
global $Input;
// Append username to the return value
$Input = $Input . $Row["Username"] . " : ";
// Append chat to the return value
$Input = $Input . $Row["Chat"] . "<br />";
}
}
// Will return the value
echo $Input;
?>
My connection to the Database is fine. I'm using it on other pages that work.
So lets assume that's not the problem. :P
Any help or insight from anyone who knows or can think of something that is wrong, I would be very grateful for.
I'm new to AJAX.
You do a wrong test with
if (document.getElementById("Text").innerHTML == "")
It should be the same way you use to get the text for sending in the AJAX
if (document.getElementById("Text").value == "")
So check its value property and not its innerHTML as input elements do not have html content..
Be careful though because your code is wide-open to SQL injection attacks.
1st : use input's value property instead innerHTML
eg. use
if (document.getElementById("Text").value == "")
instead of
if (document.getElementById("Text").innerHTML == "")
2nd : use return false; at the form's onsubmit event; to prevent current page to be refreshed as you are using ajax. Otherwise the page will get refreshed and it wont display the php page's output,
eg. use
onsubmit="SendText(); return false;"
instead of just
onsubmit="SendText();"
Try AJAX Long Polling technique for chat application. Here is example
http://portal.bluejack.binus.ac.id/tutorials/webchatapplicationusinglong-pollingtechnologywithphpandajax

Categories