Problem with AJAX chat - php

The problem is this.I want to save every message in MySQL DB and I try to do this making this javascript function:
function doWork(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// Използваните браузъри
xmlhttp=new XMLHttpRequest();
}
else
{// Кой ли ползва тези версии..
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","newmsg.php?q="+str,true);
xmlhttp.send();
}
Then the text field :
<div id="sender">
Your message: <input type="text" name="msg" size="30" id="msg" />
<button onclick="doWork(this.msg);">Send</button>
</div>
And finally the php file:
$q=$_GET["q"];
(str)$q;
$db_connect = mysql_connect('localhost', 'root', 'diamond');
if(!$db_connect)
{
die('Не може да се осъществи връзка с базата данни' . mysql_error());
}
mysql_select_db("chat", $db_connect);
$sql = "INSERT INTO messages (user_id, time, text) VALUES ('1','1234','$q')";
mysql_query($sql);
mysql_close($db_connect);
And what actually happen is that the user_id and time fields are filled properly, but the 'text' filed says "undefined".
What does it mean and how can I fix the problem(s)?
Thanks
Leron

I believe the issue is in your reference to the input text field. Try this instead:
<div id="sender">
Your message: <input type="text" name="msg" size="30" id="msg" />
<button onclick="doWork(document.getElementById('msg').value);">Send</button>
</div>
When you use the following, 'this' refers to the button element, so don't do the following.
<button onclick="doWork(this.msg);">Send</button>

doWork(document.getElementById('msg'));
this there is a button element. It has no msg property i.e. undefined, within string conversion.

Replace
<button onclick="doWork(this.msg);">Send</button>
with
<button onclick="doWork(msg);">Send</button>
this.msg is the same as button.msg, which does not make sense.

Typecast (str) doesn't exist, it's (string). And you have to do this by assignment:
$q = (string) $q;
Actually it's pretty pointless since URL's are strings. So leave that line out.
Also, as the other repliers mentioned, that's not the right way to get the value. If you do it the following way, the button will be accessible with the return key too. With onclick the user is forced to click on the button. Add return false so that the form doesn't get submitted. this points to <form>.
<form onsubmit="alert(this.msg.value); return false">
<p>
<input type="text" name="msg" />
<button type="submit">Send</button>
</p>
</form>

Related

Get connection variable from a class sent with a form

I have a problem with get the connection variable for open a database connection.
This my code in html
<form action="password.php" method="post">
<div class="form-group">
<input type="password" class="form-control" name="current" placeholder="Contraseña Actual..." />
</div>
<div class="form-group">
<input type="password" class="form-control" name="new" placeholder="Nueva Contraseña..." />
</div>
<div class="form-group">
<input type="password" class="form-control" name="confirm" placeholder="Repetir Nueva Contraseña..." />
</div>
</div>
<div class="modal-footer">
<input type="hidden" name="q" value="proofQueries">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" class="btn btn-primary"><i class="fa fa-plus"></i> Cambiar</button>
</form>
While the code of my class php
$settings = new Datasettings();
require_once('../config.php'); // file of connection of PDO
$conexion = new Conexion();
if(isset($_POST['q'])){ // get the name from html form for go to a function of this class
$settings->$_POST['q']($conexion);
}
class Datasettings {
function __construct(){
session_start();
if(!isset($_SESSION['id'])){
header('location:mystyle.css');
}
}
function proofQueries($conexion){
}
... other functions....
Could change the model how I call a the function? How I could make it?
I assume by this code:
if(isset($_POST['q'])){ // get the name from html form for go to a function of this class
$settings->$_POST['q']($conexion);
}
And submitting the hidden form field called q with value proofQueries, you are trying to call $settings->proofQueries($conexion). This is an extremely bad idea.
You are effectively executing code that comes directly from client side, which is a HUGE vulnerability risk.
It seems like a strange approach to begin with to specify the function client side, and then execute it in PHP (i.e. server side). Why specifying the q value at all, instead of just explicitly doing $settings->proofQueries($conexion) in PHP?
If you somehow must specify the function to be called client side, do something like this:
if(isset($_POST['q'])){ // get member function from submitted form
$f = $_POST['q'];
if ($f=='proofQueries') {
$settings->proofQueries($conexion);
}
else {
die("Nope");
}
}
Or if you have multiple possible functions, explicitly filter them with a whitelist to make absolutely 100% sure that ONLY the function names you decide can be called:
if(isset($_POST['q'])){ // get member function from submitted form
$f = $_POST['q'];
$allowedFunctions = array('proofQueries','doSomething','otherFunction');
if (in_array($f,$allowedFunctions)) {
$settings->$f($conexion);
}
else {
die("Nope");
}
}
But again, it seems like a strange approach alltogether. You should not specify server side specific implementation details through client side.

The button tag's form attribute causes the page reload?

First,this is my AJAX code:
<script>
function ajaxInsert() {
var xmlhttp = new XMLHttpRequest()
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("select").innerHTML = xmlhttp.responseText
}
}
var user = document.getElementById("user").value
var pwd = document.getElementById("pwd").value
var email = document.getElementById("email").value
var str = "user=" + user + "&pwd=" + pwd + "&email=" + email
// document.write(str)
xmlhttp.open("post", "getconnectforxmlhttp.php", true)
xmlhttp.setRequestHeader("content-type", "application/x-www-form-urlencoded")
xmlhttp.send(str)
}
and then,my form:
<form method="post" id="insertform">
<label for="user">用户名</label><input type="text" id="user" name="user">
<label for="pwd">密码</label><input type="password" id="pwd" name="pwd">
<label for="email">邮箱</label><input type="email" id="email" name="email">
</form>
<button form="insertform" onclick="ajaxInsert()">提交</button>
<div id="select"></div>
and last,my php code in the getconnectforxmlhttp.php file:
<?php
$pdo = new PDO("mysql:host=localhost; dbname=db_test", "root", "");
if (isset($_POST)) {
$values = "'".implode("', '", array_values($_POST))."'";
}
$str = "";
try {
$resp = $pdo->prepare("INSERT INTO user (user, pwd, email) VALUES ($values)");
$resp->execute();
} catch (Exception $e) {
$str .= "Error".$e->getMessage()."<br>";
}
if ($pdo->lastInsertId()) {
try {
$res = $pdo->prepare("SELECT * FROM user");
$res->execute();
} catch (Exception $e) {
$str .= "Error".$e->getMessage()."<br>";
}
$result = $res->fetchAll(PDO::FETCH_ASSOC);
for ($i=0; $i < count($result); ++$i) {
$str .= $result[$i]["id"]." ".$result[$i]["user"]." "
.$result[$i]["pwd"]." ".$result[$i]["email"]."<br>";
}
echo $str;
} else {
$str .= "插入失败";
echo $str;
}
?>
What it do is insert a new row into my table user in the local database,and then show them all between the div tag.but when I run this code,the insert statement successes,and the result(between the div tag) shows a second,yes,it do shows,but strangely,then it's gone,disappeared.Now I know how to do it right,simply delete the form attribute in the start button tag,and change the value of id of the div tag into something else,like:
<button onclick="ajaxInsert()">提交</button>
<div id="sel"></div>
also change AJAX code a little like document.getElementById("sel").innerHTML = xmlhttp.responseText,but with a little problem:I don't know what happened,what's the problem of the form I wrote in the first place,what the changes solve the problem?
I belive you are asking why you page will refresh when you click the button instead of running your javascript. This is probably because the button is linked to the form with its form attribute. This isn't the standard way to submit a form.
A HTML form requires a action and method attribute to submit. Without an action attribute the form will default to submit to the same page, which would explain a page refresh.
Although you intend for your form to submit using AJAX, What happens if your JavaScript breaks? What happens if your user doesn't have JavaScript enabled? In both situations your form can not submit.
Also, a HTML form is submitted using a input of type submit. This means you form may look like this;
<form method="post" action="getconnectforxmlhttp.php" onsubmit="event.preventDefault(); ajaxInsert();" id="insertform">
<label for="user">用户名</label><input type="text" id="user" name="user">
<label for="pwd">密码</label><input type="password" id="pwd" name="pwd">
<label for="email">邮箱</label><input type="email" id="email" name="email">
<input type="hidden" name="return" value="html">
<input type="submit" value="提交">
</form>
<div id="select"></div>
If this form submits without AJAX then it will submit all of its data to getconnectforxmlhttp.php. The input <input type="hidden" name="return" value="html"> will allow you to know that there is no JavaScript and the PHP should return a HTML page to display the data.
Otherwise your AJAX submits to the PHP file without the hidden input. In this case you PHP file can return just the data.
For users with JavaScript enabled the form attribute onsubmit will be used;
onsubmit="event.preventDefault(); ajaxInsert();"
This will first stop the form submitting normally, and then call your function to submit the form using AJAX.
This aproach towards JavaScript is called progressive enhancement, it allows your system to work for everyone but work better where posible. This is favoured rather than to make it not work for everyone but work better for some people

JSON Parse xmlhttp.requestText

I have a form that has a dynamic drop down select that when a value is selected it auto populates two other form fields, short and long description. I am trying to use Ajax to retrieve the short and long desc based on the value of the drop down select. I can receive the xmlhttp.responseText data and display it back on the form page but I am unable to parse the responseText out to the respective form fields.
You can see the responseText displayed above "Add New Record" title. It might be hard to read so here it is again: (I was thinking I might have the wrong format)
{"Stitl":"CHF STAFF","Ltitl":"Chief Of Staff"}
HTML file:
<form id="addForm" method="post" action="units_add.php">
<legend>Add New Record</legend>
<label for="titleOrg" class="control-label">Title Org</label>
<select class="form-control" name="titleOrg" id="titleOrg" onChange="populate(this.value)">
<option value=" "></option>
<?php
while ($rowl1l5s = $l1l5Result->fetch_assoc()) {
echo "<option value=". $rowl1l5s['l1l5']. ">";
echo $rowl1l5s['l1l5'] . "&nbsp&nbsp&nbsp&nbsp" .$rowl1l5s['Ltitl']; ;
echo "</option>";
}?>
</select>
<label for="shortDesc" class="control-label">Short Desc</label>
<input name="shortDesc" class="form-control" id="shortDesc" type="text" readonly="readonly">
<label for="longDesc" class="control-label">Long Desc</label>
<input name="longDesc" class="form-control" id="longDesc" type="text" readonly="readonly">
<button type="submit" class="btn btn-default" id="save"><i class="glyphicon glyphicon-ok glyphicon-white"></i> Save</button>
<a href="FDMAMaint_V10.php"
<button class="btn btn-default" id="cancel"><i class="glyphicon glyphicon-remove"></i> Cancel</button>
</a>
</form>
Then the user selects a value from the dynamic drop down it executes this JS function:
function populate(str)
{
if (str=="")
{
document.getElementById("shortDesc").innerHTML="";
return;
}
// Create an object
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)
{
data = xmlhttp.responseText;
document.getElementById("messages").innerHTML=xmlhttp.responseText;
document.getElementById("shortDesc").value=xmlhttp.responseText.shortDesc
document.getElementById("longDesc").value=xmlhttp.responseText.second;
}
}
xmlhttp.open("GET","getl2l5.php?q="+str,true);
xmlhttp.send();
}
I know that the following code (see below) doesn't work because it's being referenced wrong, plus it hasn't been parsed yet. I was just throwing that in there for reference as to why the form fields are "undefined"
document.getElementById("shortDesc").value=xmlhttp.responseText.shortDesc
document.getElementById("longDesc").value=xmlhttp.responseText.second;
Then the JS function goes out to the getL2L5 PHP script:
<?php
define('DBHOST','**************');
define('DBUSER','********');
define('DBPASS','**********');
define('DBNAME','**********');
//Connect to database
if (!$db = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME)) die("Can't connect to database");
// Retrieve the value from the title org drop down select
$q = $_GET['q'];
// Pull the Ltitl and Stitl based on the drop down value
$sql="SELECT Stitl, Ltitl FROM tl2l5 WHERE l1l5= '".$q."'";
// Execute the query
if (!$result = $db->query($sql))
{
die("There was an error running the query [" .$db->error. "]");
}
$data = array();
// Step through the query result and fetch the values
while ($row = $result->fetch_assoc()) {
$Stitl = $row['Stitl'];
$Ltitl = $row['Ltitl'];
$data = array( 'Stitl' => $Stitl, 'Ltitl' => $Ltitl);
}
echo json_encode($data);
?>
UPDATE:
Thank you #TimSPQR for the JSFiddle. This helped me get on the right track. I realized my issue was of my own doing. I used your JSFiddle to alert the value of var mydata and it displayed this:
then I went to my code to alert my variable and got this:
SOLUTION: Once I marked the html comments as php comments I was able to use JSON.parse on the xmlhttp.responseText and populate the two form fields referencing their correct field titles (ex: data.Stitl)

How to pass form input value to php function

I want to write a php page in which there is a html form. I want to send all input (number for example) of my form to a php function (instead of a javascript function; I make this to hide my javascript function code).
How can I send input value to php function?
Is it possible to call the php function through onclick="function(param1, param2)"?
I know that javascript is a client-side language while php is server-side.
If it is possible, how can I write the return of the function in an input field?
I want to remain in my page.
Is it correct - action="#"?
My code is:
<form action="#" method="get">
Inserisci number1:
<input type="text" name="val1" id="val1"></input>
<?php echo "ciaoooo"; ?>
<br></br>
Inserisci number2:
<input type="text" name="val2" id="val2"></input>
<br></br>
<input type="submit" value="send"></input>
</form>
Help me in the implementation of the simple php function and in the passage of values from input to function!
Thanks!
Make your action empty. You don't need to set the onclick attribute, that's only javascript. When you click your submit button, it will reload your page with input from the form. So write your PHP code at the top of the form.
<?php
if( isset($_GET['submit']) )
{
//be sure to validate and clean your variables
$val1 = htmlentities($_GET['val1']);
$val2 = htmlentities($_GET['val2']);
//then you can use them in a PHP function.
$result = myFunction($val1, $val2);
}
?>
<?php if( isset($result) ) echo $result; //print the result above the form ?>
<form action="" method="get">
Inserisci number1:
<input type="text" name="val1" id="val1"></input>
<?php echo "ciaoooo"; ?>
<br></br>
Inserisci number2:
<input type="text" name="val2" id="val2"></input>
<br></br>
<input type="submit" name="submit" value="send"></input>
</form>
You need to look into Ajax; Start here this is the best way to stay on the current page and be able to send inputs to php.
<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
This gets the users input on the textbox and opens the webpage gethint.php?q=ja from here the php script can do anything with $_GET['q'] and echo back to the page James, Jason....etc
This is pretty basic, just put in the php file you want to use for processing in the element.
For example
<form action="process.php" method="post">
Then in process.php you would get the form values using $_POST['name of the variable]
No, the action should be the name of php file. With on click you may only call JavaScript. And please be aware the hiding your code from the user undermines trust. JS runs on the browser so some trust is needed.
You can write your php file to the action attr of form element.
At the php side you can get the form value by $_POST['element_name'].
you must have read about function call . here i give you example of it.
<?php
funtion pr($n)
{
echo $n;
}
?>
<form action="<?php $f=$_POST['input'];pr($f);?>" method="POST">
<input name=input type=text></input>
</form>

How to stop php from executing the script if form POST is empty?

I have two input fields and whenever I open my page, it displays errors since at the start user has not entered any input to any of the field (& the errors are displayed because the user input is used in sql queries to retrieve data).
I just want to display those two forms at start of the page not the errors.
Both inputs are required to execute the Compare button. If user has not entered either one of the inputs it should not send request to php for scripting.
I mean the Compare button should send request only if both inputs are filled otherwise it should give a message to user to Type the required fields.
How to do this?
$trimUser= trim ($_POST['name']);
if(empty($name) || empty($name2))
{
echo "Enter a name ";
}
else if (isset($_POST['name']))
{
$name=$_POST['name'];
}
else if (isset($_POST['name2']))
{
$name2=$_POST['name2'];
}
& here is my form:
<form action="index.php" method="POST">
<input class="span3 search-query" placeholder="Type User A" type="text" name="name" id="field"/
<input class="span3 search-query" placeholder="Type User B" name="name2" type="text"
id="field2"/>
<button class="btn btn-primary" data-loading-text="Loading..." >Compare</button>
You have to use java script or jQuery for validate both fields are not empty. For Example..
<form action="index.php" method="POST" onsubmit="return validate()">
<input class="span3 search-query" placeholder="Type User A" type="text" name="name" id="field"/>
<input class="span3 search-query" placeholder="Type User B" name="name2" type="text"
id="field2"/>
<button class="btn btn-primary" data-loading-text="Loading..." >Compare</button>
</form>
<script type="text/javascript">
function validate(){
var field1 = document.getElementById('field').value;
var field2 = document.getElementById('field2').value;
if(field1 != '' && field2 != '' ){
return true;
} else{
alert('Type the required fields');
return false;
}
}
</script>
Here if Both fields are not empty then it will be allow to submit form. And In PHP script Add
if(isset($_POST) && !empty($_POST)){
//code comes here
}
I hope it will be helpful for you.
thanks
You can add a check to verify if the request is a post request :
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Place your error checking code here
}
Ehs4n is right, but I would be more specific and do something like :
if(!empty($_POST['compare'])) {
#validation
}
Your button code would have to be changed to :
<button name="compare" value="1" class="btn btn-primary" data-loading-text="Loading..." >Compare</button>
There are two reasons I would do this:
Using !empty() makes sure you don't get an error when $_POST['compare'] is empty
Checking $_POST['compare'] instead of just $_POST makes sure errors are only shown if someone clicks the button.
This last point is key because if you have multiple forms on the page or you happen to set a $_POST variable elsewhere you would still be showing errors.
Use the if condition with isset($_POST) before loading the post.i.e.,
if (isset($_POST)) {
if(empty($name) || empty($name2))
{
echo "Enter a name ";
}
else if (isset($_POST['name']))
{
$name=$_POST['name'];
}
else if (isset($_POST['name2']))
{
$name2=$_POST['name2'];
}
I simply got rid all of all the errors by adding this error_reporting(E_ERROR | E_PARSE); at the start of my code.
However if anyone want to check display validation error messages , one can do easily by what others have mentioned . i.e By using if($_Post).
Anyway ,Thank you everyone for the help.
Add if clause like
if($_POST) {
...your validation code
}
Think of redirecting people AFTER the error to the same page they were:
echo '<script>location.href=\'example.php\'</script>';

Categories