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
Related
This is my PHP code
<?php
require_once 'd:\xampp\htdocs\bpr\pdo_db.php';
$sql = "Select ID,FULL_NAMe,AGE from TRIAL";
$csv = get_csv_string($dbh, $sql);
echo "<script> var_csv='" . $csv . "' </script>";
function get_csv_string($dbh, $sql)
{
try
{
$result = $dbh->query($sql);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
if ($row == null) {
return "No Data";
}
$f = fopen('php://memory', 'r+');
foreach ($row as $field => $value) {
if (fputcsv($f, $field) === false) {
return false;
}
}
//second query gets the data
$data = $dbh->query($sql);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach ($data as $row) {
if (fputcsv($f, $row) === false) {
return false;
}
} // end record loop
rewind($f);
$csv = stream_get_contents($f);
return rtrim($csv);
} catch (PDOExepction $e) {
return $e->getMessage();
}
return $csv;
}
I am getting following error!
Instead of fputcsv(), I made my own code. But issue if found when I save the CSV to a javascript variable. Is there any other way to convert the data to CSV and pass it on to javascript?
I will convert this csv to JSON at Client side using javascript
You're trying to output a header row to CSV with the field names.
This code fails because you're looping through the $row array and attempting to write one field header at a time.
foreach ($row as $field => $value) {
if (fputcsv($f, $field) === false) {
return false;
}
}
What you want is an array with the field names in it. You can use array_keys() for that, so your code becomes
if (fputcsv($f, array_keys($row)) === false) return false;
No loop required.
I am working on a scanner reader, so I used ajax when the code is read by the scanner, it should insert data to the database. The problem is the data is not inserting.
Inside the script / Ajax - query is the variable I used to get the data (name)
var query = $('#scanned-QR').val();
fetch_customer_data(query);
$(document).on('keyup', '#scanned-QR', function(){
var query = $(this).val();
fetch_customer_data(query);
});
function fetch_customer_data(query = '')
{
$.ajax({
url:"validScan.php",
method: 'GET',
data:{query:query},
dataType: 'json',
success:function(data) {
console.log(data);
if (data.status == '1') {
decoder.stop();
alert('Sucess!');
}
else if(data.status=='0'){
decoder.stop();
alert('Fail!');
}
},
error:function(err){
console.log(err);
}
});
}
My Input/Textarea
<textarea id="scanned-QR" name="scanQR" readonly></textarea>
MySQL
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$link = mysqli_connect("localhost","root","");
mysqli_select_db($link, "schedule");
$query = $_GET['query'];
$res = mysqli_query($link,"INSERT INTO attendance (name) VALUES ('$query')");
if (mysqli_num_rows($res) > 0) {
$respose = array('status'=>'1');//1 for success
echo json_encode($respose );
} else {
$respose = array('status'=>'0');//0 for fail
echo json_encode($respose );
}
mysqli_close($link);
?>
For insert query, result will return as boolean, So mysqli_num_rows($res) won't accept boolean argument. mysqli_num_rows() expects parameter 1 to be mysqli_result
So you can simply check by below, whether it is inserted or not:
if ($res) {
$respose = array('status'=>'1');//1 for success
echo json_encode($respose);
exit;
} else {
$respose = array('status'=>'0');//0 for fail
echo json_encode($respose);
exit;
}
mysqli_close($link);
You should use exit try following code :
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$link = mysqli_connect("localhost","root","");
mysqli_select_db($link, "schedule");
$query = $_GET['query'];
$res = mysqli_query($link,"INSERT INTO attendance (name) VALUES ('$query')");
if (mysqli_num_rows($res) > 0) {
$respose = array('status'=>'1');//1 for success
echo json_encode($respose );
exit;
} else {
$respose = array('status'=>'0');//0 for fail
echo json_encode($respose );
exit;
}
mysqli_close($link);
exit;
mysqli_num_rows() is for getting the number of rows returned from a SELECT query. You need to check the number of affected rows instead.
You should also be using a prepared statement, and I also recommend that you set up MySQLi to throw errors. I also prefer the object-oriented approach.
<?php
// Configure MySQLi to throw exceptions on failure
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Init connection
$link = new mysqli("localhost", "root", "", "schedule");
$response = [];
// Prepare the statement and execute it
$stmt = $link->prepare("INSERT INTO attendance (name) VALUES (?)");
$stmt->bind_param("s", $_GET['query']);
$stmt->execute();
// Check the number of inserted rows
if ($stmt->affected_rows) {
$response['status'] = 1;
} else {
$response['status'] = 0;
}
// Close the statement and connection
$stmt->close();
$link->close();
echo json_encode($response);
I have a JQuery script that submits user input to a PHP script in the same file, and then displays the result of what the PHP script does with the input. That part works fine. The issue that I’m having is that, upon submission, the JQuery script (at least, I think it's the script) also generates a new submission box below the original.
I’m not sure why. I thought at first that it was an issue with the input type, with the asynchronous part, or even with where I had the form in the overall code, but none of those seem to be playing any role. I'm still a beginner and I'm just not seeing the issue.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<form id = "my_form">
verb <input type = "text" id ="word1"/>
<input type = "submit"/></form>
<div id="name"></div>
<script>
$(document).ready(function(){
$("#my_form").on('submit', function(e)
{
e.preventDefault();
var verb = $ ("#word1").val();
var tag = "#Latin ";
var url = "http://en.wiktionary.org/wiki/"+verb+tag;
$.ajax({
url: "Parser.php",
data: {"verb": verb},
type: "POST",
async: true,
success: function(result){
$("#name").html(result);
$("#name").append(url);
}
});
});
});</script>
RESULT:
PHP
<?php
$bank = array();
function endsWith($haystack, $needle) {
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}
function check_end_array($str, $ends)
{
foreach ($ends as $try) {
if (substr($str, -1*strlen($try))===$try) return $try;
}
return false;
}
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('127.0.0.1','username','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$y = false;
if (isset($_POST['verb'])){
$y=db_quote($_POST['verb']);
echo $y;
echo "\n";
$m = db_query("SELECT `conjugation` FROM normal_verbs WHERE (" . $y . ") LIKE CONCAT('%',root,'%')");
if($m !== false) {
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
foreach ($rows as $key => $value){
if (in_array("first",$value)==true){
echo "first conjugation verb\n";}
$y = $_POST["verb"];
$x = $y;
foreach ($bank as $key => $value)
(series of IF-statements)
}}?>
As Roamer-1888 says's the problem lies in server side, you are returning a html which has a input too. You need to change your code to return only the result string which you append to the div. Else if this is not possible doing at server side as it might require you to change lot of code, then you can strip off the input element from the result and then append it to the div. Like below.
success: function(result){
var div = document.createElement('div');
div.innerHTML = result;
$(div).find('input').remove();
$("#name").html(div.innerHTML);
$("#name").append(url);
}
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 have a small doubt.. i posted my delete.php page coding here.
if(isset($_GET["id"]))
{
$meal_query = mysql_query("DELETE FROM ebmealplans WHERE MealPlanID = '$id'");
echo mysql_error();
$room_query = mysql_query("DELETE FROM ebroomtypes WHERE RoomTypeID = '$id'");
echo mysql_error();
$tariff_query = mysql_query("DELETE FROM ebvouchertariffs WHERE VoucherID_Fk = '$id'");
echo mysql_error();
$query = mysql_query("DELETE FROM ebvouchers WHERE VoucherID = '$id'");
echo mysql_error();
if($query)
{
echo "<script> alert('Voucher deleted successfully'); </script>";
}
else
{
echo "<script> alert('Failed to delete this voucher'); </script>";
}
mysql_close($link);
echo "<script> location.href='managevouchers.php'; </script>";
}
here i am delete some user datas using this php coding. it worked perfectly. i created four separate tables for store the records. if deletion function was successfully completed i want to show the alert message to users "Deleted Successfully". you can see in my coding i'm just show the alert message for only one $query. i tried another method..
if($query)
{
alert function
}
else
{
alert function
}
if($meal_query)
{
alert function
}
else
{
alert function
}
if($room_query)
{
alert function
}
else
{
alert function
}
if($tariff_query)
{
alert function
}
else
{
alert function
}
it show the alert message four times. i know multiple alert functions annoying the users. my question is how to show the single alert message for mysql multiple queries?
Just store the msg pieces in some variable, and alert them all finally.
$msgs = array ();
if ($query) {
$msgs [] = '.....';
} else {
$msgs [] = '...';
}
if ($meal_query) {
$msgs [] = '....';
} else {
$msgs [] = '...';
}
//....
if ($msgs) {
//join the msgs with line break
$alert = join ( "\n", $msgs );
//json encode will make sure it's like "..string..", no quotes problem
echo '<script> alert(', json_encode ( $alert ), '); </script>';
}