i have 2 file tst.html and tst.php
tst.html body is
<form>
<input id="search" type="text" size="30" onkeyup="showresult(this.value)" >
<div id="suggest"></div>
</form>
<script>
function showresult(val){
if(val.trim() == ""){
}else{
var xttp = new XMLHttpRequest() ;
xttp.onreadystatechange = function () {
var s = xttp.responseText ;
if(s.match("zerorow")){
document.getElementById("suggest").innerHTML = "zero" ;
}else {
try {
window.alert(s) ;
var arr = JSON.parse(s) ;
}
catch(err) {
document.getElementById("suggest").innerHTML = err.message;
}
}
};
xttp.open("POST" , "tst.php" ,true) ;
xttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded") ;
xttp.send("val="+val) ;
}
}
and tst.php
<?php
$servername = "localhost";
$dbusername = "mamad";
$dbpassword = "";
$dbname = "t1" ;
// Create connection
$conn = mysqli_connect($servername, $dbusername, $dbpassword , $dbname);
if (!$conn) {
die("Connection failedddddddddd: " . mysqli_connect_error());
}else{
$val = $_POST["val"] ;
$sql = "SELECT tag FROM tags WHERE tag LIKE '$val%'";
$result = mysqli_query($conn, $sql);
if($result){
if(mysqli_num_rows($result) > 0){
$arr = mysqli_fetch_all($result , MYSQLI_NUM) ;
echo json_encode($arr) ;
}else{
echo "zerorow" ;
}
}else{
echo die("faileddd " . mysqli_connect_error());
}
}
?>
assume in my database i have two record tag1 and tag2 in tag column
and
$arr = mysqli_fetch_all($result , MYSQLI_NUM) ;
json_encode($arr) ;
if you input t alphabet in input field tst.php
pass a 2 dimensional array as string like this [["tag1"],["tag2"]]
but
var arr = JSON.parse(s) ;
throw a syntax error with JSON.parse: unexpected end of data at line 1 column 1 of the JSON data message
and one more question i just want want column of data of table in my database is there any function that do it and give one dimensional array ?
sorry if it become long question .
The onreadystatechange event fires on every state change, not only if the request is finished and the result is returned.
You have to add some checks to make it work:
The readyState must be in status DONE, and
the http status must be 200
In code that looks like this:
xttp.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xttp.status === 200) {
var s = xttp.responseText ;
if(s.match("zerorow")){
document.getElementById("suggest").innerHTML = "zero" ;
} else {
try {
window.alert(s) ;
var arr = JSON.parse(s) ;
} catch(err) {
document.getElementById("suggest").innerHTML = err.message;
}
}
}
};
Hint: Better use only one return type. In your case JSON. In your code your mixing up different content types. That's bad style
Furthermore your sql is attackable with sql injections. This is an security and safty issue
Related
my coding is all about
1)fetch the data from mysql thro php
2)get data from php to d3 based on input by using PHP URL
I want to set alert when the text in the input field is not found in mysql database..
now when I try with the word other than mysql data, it shows
this console
how can i alert when wrong word(other than mysql database value) is submitted
HTML FORM
<form name="editorForm">
<input type="text"name="editor" id="editor"
onchange="document.getElementById('editorForm').submit();">
<input type="submit"value="butn">
</form>
JQUERY TO FETCH THE DATA FROM PHP BASED ON URL
$(function () {
$('form').submit(function (e) {
e.preventDefault();
var t=$('form').serialize();
var u='http://localhost:8888/saff/indexi.php?'+t;
if(u==null){
alert("not found");
}
else{
funn();
}
D3 CODES
function funn(){
d3.json(u, function(treeData) {
//D3 CODES
});
}
my php code
<?php
$con=mysqli_connect("localhost","root","admin","data");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['editor'];
$sql="SELECT * FROM phptab where value LIKE '%".$name."%'";
$r = mysqli_query($con,$sql);
$data = array();
while($row = mysqli_fetch_assoc($r)) {
$data[] = $row;
}
function buildtree($src_arr, $parent_id = 0, $tree = array())
{
foreach($src_arr as $idx => $row)
{
if($row['parent'] == $parent_id)
{
foreach($row as $k => $v)
$tree[$row['id']][$k] = $v;
unset($src_arr[$idx]);
$tree[$row['id']]['children'] = buildtree($src_arr, $row['id']);
}
}
ksort($tree);
return $tree;
}
function insertIntoNestedArray(&$array, $searchItem){
if($searchItem['parent'] == 0){
array_push($array, $searchItem);
return;
}
if(empty($array)){ return; }
array_walk($array, function(&$item, $key, $searchItem){
if($item['id'] == $searchItem['parent']){
array_push($item['children'], $searchItem);
return;
}
insertIntoNestedArray($item['children'], $searchItem);
}, $searchItem);
}
$nestedArray = array();
foreach($data as $itemData){
//$nestedArrayItem['value'] = $itemData['value'];
$nestedArrayItem['id'] = $itemData['id'];
$nestedArrayItem['name'] = $itemData['name'];
$nestedArrayItem['parent'] = $itemData['parent'];
$nestedArrayItem['tooltip'] = $itemData['tooltip'];
$nestedArrayItem['color'] = $itemData['color'];
$nestedArrayItem['level'] = $itemData['level'];
$nestedArrayItem['children'] = array();
//$data[]=$dat;
insertIntoNestedArray($nestedArray, $nestedArrayItem);
}
header('Content-Type: application/json');
$json= json_encode($nestedArray,JSON_UNESCAPED_UNICODE);
echo $json = substr($json, 1, -1);
?>
works as expected when the word used is exist in the database
and the page looks like this
getting correct json format in the mozilla console.but design is not shown in the page...but in chrome ,everything works fine..
You need to test if the page is empty in the json function of the d3
function funn(){
d3.json(u, function(treeData) {
if(!treeData.length){
alert("not found");
}else {
//D3 CODES
}
});
}
Make sure that you return a empty object from the page when not found
im using checkfile to upload file by Month & Year .
If success it will load the data to database.
IF checkfile = false
I want to display an alert message ("import Fail")
foreach ($files1 as &$value) {
$checkfile = strpos($value,$input1 );
if($checkfile === false) {
//echo "<script>alert('Import Fail ');</script>";
}
else
{
echo "Import $value successfully! <br>" ;
$query = "load data local infile '//192.168.100.3/Groups/$location1/Timesheet/$value'
replace
$result = $connection->query($query) or exit("Error code ({$connection->errno}): {$connection->error}");
}
}
unset($value);
?>
I tried to have echo alert('Import Fail ');
but it give me multiple alert every single file from the folder .
Way1 : Manage the flow with flag as below. If any of the file successfully imported then change the flag and then make a condition on the flag to display alert.
$flag = 0;
foreach ($files1 as &$value) {
$checkfile = strpos($value,$input1 );
if($checkfile === false) {
//echo "<script>alert('Import Fail ');</script>";
}
else
{
$flag = 1;
echo "Import $value successfully! <br>" ;
// $query1 =
// "Delete FROM hklcanet_pha.psr this
// WHERE year(psr.ReportDate) = $input3
// AND month(psr.ReportDate) = $input2";
$query = "load data local infile '//192.168.100.3/Groups/$location1/Timesheet/$value'
replace
into table hklcanet_pha.psr fields terminated by ','
optionally enclosed by '\"'
lines terminated by '\n'
ignore 1 lines
(`ReportDate`, #dummy, #dummy, `Team_refno`,`Name/Description`,`Status`,`PIC`,`RequestDate`,`TargetEndDate`,`ActualEndDate`,`PlanStartDate`,`ActualStartDate`,`PlanUATDate`,`ActualUATDate`,`PlanImplement`,`ActualImplement` )";
//echo "Import $value successfully! <br>" ;
$result = $connection->query($query) or exit("Error code ({$connection->errno}): {$connection->error}");
}
}
if($flag == 1){
echo "<script>alert('Import Fail ');</script>";
}
unset($value);
?>
Way 2: Get the name of successfully imported file names and make conditions on it.
$flag = [];
foreach ($files1 as &$value) {
$checkfile = strpos($value,$input1 );
if($checkfile === false) {
//echo "<script>alert('Import Fail ');</script>";
}
else
{
//Store successful file names in array
$flag[] = $value;
echo "Import $value successfully! <br>" ;
// $query1 =
// "Delete FROM hklcanet_pha.psr this
// WHERE year(psr.ReportDate) = $input3
// AND month(psr.ReportDate) = $input2";
$query = "load data local infile '//192.168.100.3/Groups/$location1/Timesheet/$value'
replace
into table hklcanet_pha.psr fields terminated by ','
optionally enclosed by '\"'
lines terminated by '\n'
ignore 1 lines
(`ReportDate`, #dummy, #dummy, `Team_refno`,`Name/Description`,`Status`,`PIC`,`RequestDate`,`TargetEndDate`,`ActualEndDate`,`PlanStartDate`,`ActualStartDate`,`PlanUATDate`,`ActualUATDate`,`PlanImplement`,`ActualImplement` )";
//echo "Import $value successfully! <br>" ;
$result = $connection->query($query) or exit("Error code ({$connection->errno}): {$connection->error}");
}
}
if(sizeof($flag) == 0){
//Display all the file names in alert
$failedFiles = implode(",",$flag);
echo "<script>alert('Import Failed for files : ".$failedFiles."');</script>";
}
unset($value);
?>
function create(x) {
var field=document.createElement('fieldset');
var t=document.createElement('table');
t.setAttribute("id","myTable");
document.body.appendChild(t);
field.appendChild(t);
document.body.appendChild(field);
var row=document.createElement('th');
newHeader = document.createElement("th");
newHeader.innerText = x;
row.appendChild(newHeader);
var row1=document.createElement('tr');
var col1=document.createElement('td');
var col2=document.createElement('td');
var row2=document.createElement('tr');
var col3=document.createElement('td');
var col4=document.createElement('td');
var row3=document.createElement('tr');
var col5=document.createElement('td');
var col6=document.createElement('td');
col1.innerHTML="Name";
col2.innerHTML="<input type='text' name='stateactivityname' size='40' required>";
row1.appendChild(col1);
row1.appendChild(col2);
col3.innerHTML="Registration Applicable";
col4.innerHTML="<select name='regapp' required><option></option><option>Yes</option><option>No</option></select>";
row2.appendChild(col3);
row2.appendChild(col4);
col5.innerHTML="Registers Applicable";
col6.innerHTML="<select name='registers' required><option></option><option>Yes</option><option>No</option></select>";
row3.appendChild(col5);
row3.appendChild(col6);
t.appendChild(row);
t.appendChild(row1);
t.appendChild(row2);
t.appendChild(row3);
addrow('myTable');
}
PHP code for storing data to database is:
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
$conn=new mysqli("localhost","root","","newcomplyindia");
if($conn->connect_errno){
echo("connection error");
}
$actname=$_POST["actname"];
$industry=$_POST['industrytype'];
$centralorstate=$_POST["cors"];
$sql="insert into acts (actname,centralorstate) value ('".$actname."','".$centralorstate."')";
$regapp=$_POST["regapp"];
if($regapp=='Yes'){
$regapp=true;
}
else{
$regapp=false;
}
$registers=$_POST["registers"];
if($registers=='Yes'){
$registers=true;
}
else{
$registers=false;
}
$sub=$_POST["sub"];
if($sub=='Yes'){
$sub=true;
}
else{
$sub=false;
}
if($conn->query($sql)==true){
echo 'act name added ';
}
$lastid=$conn->insert_id;
$sql1="insert into actsstate (actid,registrationrequired,registersapplicable,sublocation)"
. "values('$lastid','$regapp','$registers','$sub')";
if($conn->query($sql1)==true){
echo '<br>name and central/state added';
}
$stateactivity=$_POST["stateactivityname"];
$activityname=$_POST["activityname"];
$activitymonth=$_POST["month"];
$activitydate=$_POST["date"];
$sql2="insert into activity (name,actid,activityname,activitymonth,activitydate)"
. "values('$stateactivity','$lastid','$activityname','$activitymonth','$activitydate')";
if($conn->query($sql2)){
echo 'activity added';
}
else{
echo 'no record';
}
$conn->close();
?>
i have a javascript like this. The table is created dynamically. And i want to store the data inside this table to database. am using mysqli for database connection
Am new to javascript. Can anyone help me to do this
Here's a way using Vanilla JS (pure js)
var xhttp = new XMLHttpRequest();
var url = "save.php";
xhttp.open("POST", url, true);
// uncomment this if you're sending JSON
// xhttp.setRequestHeader("Content-type", "application/json");
xhttp.onreadystatechange = function() { // Call a function when the state changes.
if(xhttp.readyState == 4 && xhttp.status == 200) {
// the 4 & 200 are the responses that you will get when the call is successful
alert(xhttp.responseText);
}
}
xhttp.send('the data you want to send');
And here's a way to save to the database (mysql in my case) with Flat PHP (pure php)
$servername = "localhost";
$username = "db_username";
$password = "db_password";
$dbname = "db_name";
// connect to the DB
$conn = new mysqli($servername, $username, $password, $dbname);
// check if you're connected
if ($conn->connect_error) {
echo "Connection failed: " . $conn->connect_error;
}
else {
// echo "connecting to DB succeeded <br> ";
}
// uncomment the following if you're recieving json
// header("Content-Type: application/json");
// $array = json_decode(file_get_contents("php://input"), true);
$sql = "INSERT INTO table_name (columns,names) VALUES (columns,values)";
if ($conn->query($sql) === TRUE) {
echo "Data was saved successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
to learn more about the sql commands I suggest the w3schools tutorials
Of course you can by using AJAX:
$.post("php_script.php",{javascript variables}, function(result) {
alert(result);
});
I have an input box in html. The input searches an database through ajax and return the results in front-end. The problem is that I don't get the result from PHP. I don't know what I did wrong, so I hope you guys have a better understanding from me.
HTML
<body onload="AjaxFindPerson()">
.....
</body>
JS
var xmlHttp = createXmlHttpRequestObject();
function AjaxFindPerson() {
if ((xmlHttp.readyState == 0 || xmlHttp.readyState == 4) && document.getElementById("PersonSearchInput").value != "") {
person = encodeURIComponent(document.getElementById("PersonSearchInput").value);
xmlHttp.open("GET", "../lib/search.php?email=" + person, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else {
document.getElementById('Label-Result').innerHTML = "";
document.getElementById('UserNameSearchResult').innerHTML = "";
$('#add-person-btn').attr("disabled", "disabled");
setTimeout('AjaxFindPerson()', 1000);
}
}
function handleServerResponse() {
if (xmlHttp.readyState == 4 ) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
result = xmlDocumentElement.firstChild.data;
if (result[0] != false) {
document.getElementById('Label-Result').innerHTML = result[1];
document.getElementById('UserNameSearchResult').innerHTML = result[0];
$('#add-person-btn').removeAttr("disabled", "disabled");
}
else {
document.getElementById('Label-Result').innerHTML = result[1];
}
setTimeout('AjaxFindPerson()', 1000);
}
else {
alert('Somenthing went wrong when tried to get data from server'+ xmlHttp.readyState);
}
}
}
PHP
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
session_start();
define("DB_HOST", 'mysql6.000webhost.com');
define("DB_USER", '');
define("DB_PASSWORD", '');
define("DB_DATABSE", '');
echo '<response>';
$email = $_GET['email'];
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_DATABSE, $conn);
$sq = mysql_query("SELECT UserEmail FROM Users");
$UserInfo = array();
while ($row = mysql_fetch_array($sq, MYSQL_ASSOC)) {
$UserInfo[] = $row['UserEmail'];
}
if (in_array($email, $UserInfo)) {
$result = mysql_query("SELECT UserName FROM Users WHERE UserEmail = '".$email."'");
$row = mysql_fetch_row($result);
$returnRes = array($row[0], "We found results"); //row[0] holds the UserN
echo $returnRes;
}
else {
$returnRes = array(false, "We couldn't find results");
echo $returnRes;
}
echo '</response>';
?>
If we check the php-xml file alone will see the image bellow :
Do I need to pass the values to xml-php with another way?
UPDATE 1 in PHP
I manage to found a way to return the data correctly. Here are the update 'touch'
header('Content-Type: application/json');
and
if (in_array($email, $UserInfo)) {
$result = mysql_query("SELECT UserName FROM Users WHERE UserEmail = '".$email."'");
$row = mysql_fetch_row($result);
echo json_encode(array( 'found' => $row[0], 'msg' => "We found results"));
}
else {
echo json_encode(array( 'found' => null, 'msg' => "We couldn't find results"));
}
The problem now is how to manipulate the js file to handle the return array. I made a try but it didn't worked:
result = xmlDocumentElement.firstChild.data;
if (result['found'] != null) {
document.getElementById('Label-Result').innerHTML = result['msg'];
document.getElementById('UserNameSearchResult').innerHTML = result['found'];
$('#add-person-btn').removeAttr("disabled");
}
else {
document.getElementById('Label-Result').innerHTML = result['msg'];
}
**UPDATE 2 WORKING JS **
I figure out how to retrieve the data from PHP.
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
var result = JSON.parse(xmlDocumentElement.firstChild.data);
if (result['found'] != null) {
document.getElementById('Label-Result').innerHTML = result['msg'];
document.getElementById('UserNameSearchResult').innerHTML = result['found'];
$('#add-person-btn').removeAttr("disabled");
}
else {
document.getElementById('Label-Result').innerHTML = result['msg'];
}
NOW ALL THE CODE IS WORKING! THANK YOU VERY MUCH GUYS!
+1 to all of you!
Four things :
Usage of send(null) doesn't seems to be right, just don't pass null in it.
Second one is timeout method. Instead the way you are using it, you can call it in the callback function or instead of string use the name at the function call.
The usage to remove the attribute is also wrong. It is currently using a set method as you have supplied a second argument. The remove attribute method only takes a attribute name.
I would rather suggest you to set a header for the application/json and use json_encode() method to return data.
For printing an array, you can either use json_encode(), or do somehow else transform your array into a string.
If we were to ignore the white elephant in the room and gloss over the use of mysql_* functions then a slightly different approach
<?php
session_start();
define('DB_HOST', 'mysql6.000webhost.com');
define('DB_USER', '');
define('DB_PASSWORD', '');
define('DB_DATABASE', '');
$dom=new DOMDocument('1.0','utf-8');
$root=$dom->createElement('response');
$dom->appendChild( $root );
if( $_SERVER['REQUEST_METHOD']=='GET' && isset( $_GET['email'] ) ){
/* Basic filtering IF mysql_* functions are used! */
$email = trim( strip_tags( filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL ) ) );
$conn = mysql_connect( DB_HOST, DB_USER, DB_PASSWORD );
mysql_select_db( DB_DATABASE, $conn ) or die('error: database connection failed');
/* By the looks of the original there should be no need for two queries and then an array lookup */
$result = mysql_query("SELECT `UserName` FROM `Users` WHERE `UserEmail` = '".$email."';");
/* If there are results, add nodes to the dom object */
if( mysql_num_rows( $result ) > 0 ){
while( $rs=mysql_fetch_object( $result ) ){
$root->appendChild( $dom->createElement( 'user', $rs->UserName ) );
}
} else {
/* Otherwise add error message */
$root->appendChild( $dom->createElement( 'error', 'We couldn\'t find any results!' ) );
}
}
/* Send the xml back to the js client */
header('Content-Type: text/xml');
$xml=$dom->saveXML();
$dom=null;
exit( $xml );
?>
I am using this code right here:
HTML code (jsonexamplecss.html):
<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "adomaniname/phpselectdatawhere.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var s = 256;
var hr = new XMLHttpRequest();
hr.open("POST", "adomainname/phpselectdatawhere.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send("limit="+s);
var arr = JSON.parse(response);
var i;
var i = 0;
for(i = 0; i < arr.length; i++) {
out = arr[i].name
if (out = "0 results") {
alert("0 results");
}
}
document.getElementById("id01").innerHTML = out;
alert(out);
}
</script>
</body>
</html>
PHP code(phpselectdatawhere.php):
<?php
if(isset($_POST['limit'])){
$limit = preg_replace('#[^0-9]#', '', $_POST['limit']);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM testget WHERE id='$limit'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"];
}
} else {
echo "0 results";
}
$conn->close();
?>
I have a table named testget with id, name fields both VARCHAR. I wrote a script in order to do these things:
The HTML script sends data to the php script via http request and in this example it sends limit=256.
The PHP script gets the limit=256, puts away the number from the limit and stores $limit =256.
After that the PHP script searches if there is a name in the table whose id='$limit' and prints the name if it exists, else it echoes 0 results. The table testget has a row where id=256 and name=JohnDoe so it can't echo 0 results.
After all this procedure the HTML scripts gets the echoed stuff and alerts them with JavaScript.
So in this case I want to have JohnDoe alerted in my HTML page but unfortunately nothing shows up. Could you please help me?
Note that the url and the database connection info are correct but as you can understand I don't want to show them.