JQuery Autocomplete's source from db using json - javascript

I'm trying to make jquery autocomplete input field with source from database, and the data is stored in json. I stored all data I got in one variable, it's look like this :
and when I set source to be value of that sinput field, I got the whole sentece (which is expect from my example)..but now I know to have three words (first - skijanje, second - vodopoad, third - more) so to have three options in my autocomplete. Here is my code for getting data using php:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "user_name", "user_pass", "db_name");
$result = $conn->query("SELECT `title`, `type` FROM " . $obj->table);
$output = array();
$output = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($output);
Here is js code for reading that data :
<script>
var obj, dbParam, xmlhttp,x , txt = "";
var i = 0;
obj = { "table":"tourplan" };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = "All data: " + this.responseText;
var myObj = JSON.parse(this.responseText);
for (x in myObj) {
txt += myObj[x].title +" ";
}
document.getElementById("demo2").value = txt;
//document.getElementById("demo2").innerHTML = "Only one field: " + myObj[1].title;
}
}
xmlhttp.open("GET", "tourTitle.php?x=" + dbParam, true);
xmlhttp.send();
</script>
<p id="demo"></p>
<input type="text" id="demo2" value="">
for document.getElementByID('demo').innerHTML = "All data: " + this.responseText; I got this:
All data: [{"title":"skijanje","type":"zima"},{"title":"vodopad","type":"jesen - proljece - ljeto"},{"title":"more","type":"ljeto"}]
and here is for making autocomplete:
<script>
$( function() {
var otherPlaces = [
txt
];
$("#search-loged").autocomplete({
source: txt
});
});
</script>
ANy idea for correct that? thanks

Don't use pure ajax, try something like this:
jQuery Ajax
$( function() {
$("#search-loged").autocomplete({
source: 'tourTitle.php',
minLength: 2,
select: function( event, ui ) {
log( "Selected: " + ui.item.value + " aka " + ui.item.id );
}
});
});
HTML
<p id="demo"></p>
<input type="text" id="demo2" value="" name='x'>
PHP
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);
$conn = new mysqli("localhost", "user_name", "user_pass", "db_name");
$result = $conn->query("SELECT `title`, `type` FROM " . $obj->table);
$output = array();
$output = $result->fetch_all(MYSQLI_ASSOC);
$response = array();
foreach($output as row){
$response[] = ["value"=>$row['title'],"label"=>$row['title']];
}
echo json_encode($response);

Related

How to add data from database into object in php for temporary using while loading

I am new in php . I have the following code to retrieve categorytype data from database?. I want to add them into php object for temporary using while loading page. First, I want to load all predefined data, then i will use it when i click function. Could you enlighten me how to create it
categoryDao.php
namespace category;
use Exception;
use PDO;
class categoryDao{
public function categorytype(PDO $connection){
$conn = $connection;
try {
$conn = $connection;
$sql="SELECT * FROM `tb_category` WHERE id != parent_id;";
$categorytype = $conn->prepare($sql);
$categorytype->execute();
$data1 = array();
while (
$result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
return $data1;
} catch (Exception $e) {
echo $e;
throw $e;
}
}
}
categoryservice.php
use category\categoryDao;
require '../dao/categoryDao.php';
require 'Dao.php';
class categoryService{
public function categorytype(){
$dao = new Dao();
$conn= $dao->connect();
$conn->beginTransaction();
$categoryDao = new categoryDao();
//$data1 = array();
$data1=$categoryDao->categorytype($conn);
return $data1;
$dao->disconnect($conn);
}
}
categorytypecontroller.php
<?php
require '../service/categoryService.php';
require '../service/categoryService.php';
$categoryname = #trim(stripslashes($_POST['category']));
$category = new categoryService();
//$ctype = array();
$ctype = $category->categorytype();
$return["json"] = json_encode($ctype);
echo $return["json"];
Head.php
function categorytype() {
//var hosname =window.location.protocol + "//" + window.location.hostname + window.location.pathname;
var hosname1 = window.location.protocol + "//" + window.location.hostname+ "/servicegateway/sgw/modules/controller/categorytypecontroller.php";
alert (hosname1);
//var ur = hosname + "/modules/controller/categorycontroller.php";
$.ajax({
url:hosname1 , //the page containing php script
type: "POST", //request type,
dataType: 'json',
data: '',
success:function(data1){
alert(data1);
var obj =data1;
// var leng = Object.keys(obj).length;
var areaOption = "<option value=''>Select Category </option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#c_type").html(areaOption);
}
});
}
A couple of things. If you want the data to be an array of records, you'll probably want to change this part:
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = $result['id'];
$data1[] = $result['c_name'];
}
as that is putting all the fields, one after the other, into a normal array.
while ($result = $categorytype->fetch(PDO::FETCH_ASSOC)) {
$data1[] = array(
'id' => $result['id'],
'c_name' => $result['c_name']
);
}
That will create a small associative array of the id and name fields and put it into another array, with the other records. PHP associative arrays will turn into Javascript objects when sent via ajax.
Then, in Javascript, you'll want to make use of those objects to create your options, so:
areaOption += '<option value="' + obj[i].id + '">' + obj[i].c_name + '</option>'

Posting data without refresh + calling another jquery function

My code, basically, on a click of a button, runs an ajax function in order to write stuff to my database.
What I want to do next is call another function which will fetch data from the database and print it.
Here is my code below, but the second function does not show that it works. I don't know where I went wrong.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function loaddata() {
$.ajax({
type: "POST",
url: "includes/fetchupdatedimages.php",
data: $("#editad_form").serialize(),
success: function (response) {
alert(response);
}
});
});
</script>
Second function:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$("#deleteimgs").click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "includes/deleteimages.php",
data: $("#editad_form").serialize()
});
$("input[type=checkbox]:checked").parent().remove();
loaddata();
});
});
</script>
fetchupdatedimages.php
<?php
include_once "functions.php";
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
error_reporting(-1);
error_reporting(E_ALL);
$id = $_POST["id"];
if ($stmt = $mysqli->prepare("SELECT images FROM db WHERE id = ? LIMIT 1")) {
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($images);
$stmt->fetch();
}
echo "<p>" . $images . "</p>";
?>
It seems that loaddata() does not get called or it does not return any data to me back. Any help?
Have you tried sending the data from your PHP file using JSON over to your jQuery code instead?
For example:
PHP
<?php
header("Content-Type: application/json");
include 'connect.php';
$sql = "SELECT * FROM reviews, customers WHERE review_user = customer_id";
$datas = "";
$x = 0;
$result = $con->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$datas[$x] = array("fname" => $row["customer_name"], "lname" => $row["customer_surname"], "email" => $row["customer_email"], "gender" => $row["customer_gender"], "title" => $row["review_title"], "content" => $row["review_content"], "rating" => $row["review_rating"]);
$x++;
}
}
$con->close();
echo json_encode($datas);
?>
jQuery
$(document).ready(function() {
$.getJSON('controls/getReviews.php', function(jsondata) {
console.log("Returned data: " + jsondata);
if (jsondata !== "") {
for (var i = 0; i < jsondata.length; i++) {
var data = jsondata[i];
var fname = data["fname"];
var lname = data["lname"];
var email = data["email"];
var gender = data["gender"];
var title = data["title"];
var msg = data["content"];
var rating = data["rating"];
$('.reviews').append('<div class="panel panel-default"><div class="panel-heading"><h3 class="panel-title">' + title + '</h3></div><div class="panel-body"><table class="table table-striped"><tr><td>Name:</td><td>' + fname + ' ' + lname + '</td></tr><tr><td>Gender:</td><td>' + gender + '</td></tr><tr><td>Rating:</td><td>' + rating + '/5</td></tr><tr><td>Message:</td><td>' + msg + '</td></tr></table></div></div>');
}
}
});
});

js,mysql,php - Get specific result in the ajax request via while loop

I want to display only a certain result via ajax when I click on a button while it is in the while loop.
while($row = mysql_fetch_array($rs_admin))
{
echo ("<h3>" .$row['emer_type'] . "</h3> ");
echo ("<p>".$row['emer_desc'] . "</p>");
echo '<div class="button"><button type="button" onclick="loadDoc()">Change Content</button></div>':
echo '<div id="demo"><p>I WANT TO PUT IT HERE</p></div>';
}
They have their very own ID so that they know what they will fetch.
This is the ajax that I've got
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "test.php", true);
xhttp.send();
}
</script>
The test.php is this
<?php
include 'includes/db_connection.php';
$sel_admin = "select * from ehr_cm_emergency ";
$rs_admin = mysql_query($sel_admin);
while ($row = mysql_fetch_array($rs_admin))
{
echo $row['emer_more'];
}
?>
However when I'm clicking the button in the second or third button, the result is displaying in the first one.
Differentiate the id by auto increment and pass it to the function, and apply to the text to the id like following,
<?php
$i=0;
while($row = mysql_fetch_array($rs_admin))
{
$i++;
echo ("<h3>" .$row['emer_type'] . "</h3> ");
echo ("<p>".$row['emer_desc'] . "</p>");
echo '<div class="button"><button type="button" onclick="loadDoc(\'demo'.$i.'\')">Change Content</button></div>';
echo '<div id="demo'.$i.'"><p>I WANT TO PUT IT HERE</p></div>';
}
?>
<script>
function loadDoc(id) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById(id).innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "test.php", true);
xhttp.send();
}
</script>
For specific Row based
I used emp_id for unique, change your value
<?php
$i=0;
while($row = mysql_fetch_array($rs_admin))
{
$i++;
echo ("<h3>" .$row['emer_type'] . "</h3> ");
echo ("<p>".$row['emer_desc'] . "</p>");
echo '<div class="button"><button type="button" onclick="loadDoc(\'demo'.$i.'\','.$row['emp_id'].')">Change Content</button></div>';
echo '<div id="demo'.$i.'"><p>I WANT TO PUT IT HERE</p></div>';
}
?>
<script>
function loadDoc(id,empid) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById(id).innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "test.php?empid="+empid, true);
xhttp.send();
}
</script>
<?php
include 'includes/db_connection.php';
$sel_admin = "select * from ehr_cm_emergency where emp_id=".$_GET['emp_id'];
$rs_admin = mysql_query($sel_admin);
while ($row = mysql_fetch_array($rs_admin))
{
echo $row['emer_more'];
}
?>

Javascript AJAX upload of BLOB image using php. $_FILES is empty

Hi I am trying to upload a BLOB image onto my localhost wampserver through AJAX using Javascript and PHP.
I am trying to obtain the image in $_FILES but for some reason $_FILES is empty. I have set enctype and checked php.ini for file_uploads = On.
Here is my html form:
<h1>CREATE A NEW ENTRY</h1>
<form name="insertForm" method="post" enctype="multipart/form-data">
Name: <input type="text" id="insert_name" /> <br />
Age: <input type="text" id="insert_age" /> <br />
WPM: <input type="text" id="insert_wpm" /> <br />
Sex: <select id="insert_sex">
<option>M</option>
<option>F</option>
</select><br />
Photo : <input type="file" name="photo" id="insert_photo" /> <br />
<input type="button" onClick="insertFunction()" value="UPDATE LIST" />
</form>
<br>
<br>
<div id="preview"><img id="preview_img" src="images/placeholder.png"/></div>
<div id="message"></div>
Here is the javascript that runs the AJAX :
function insertFunction()
{
var ajaxRequest = createAjaxObject(); // checks for browser type and returns corres. ajax object
var name = document.getElementById('insert_name').value;
var age = document.getElementById('insert_age').value;
var wpm = document.getElementById('insert_wpm').value;
var sex = document.getElementById('insert_sex').value;
var image = document.getElementById('insert_photo').files[0];
var imageType = image.type;
alert(imageType);
var match = ["image/jpeg", "image/png", "image/jpg"]
if (!((imageType==match[0]) || (imageType==match[1]) || (imageType==match[2])))
{
document.getElementById('preview').innerHTML = '';
document.getElementById('preview').innerHTML = '<img id="preview_img" src="images/noimage.png"/ alt="../images/noimage.png">';
document.getElementById("message").innerHTML = "<p class='error'>Please Select A valid Image File</p>"+"<h4>Note</h4>"+"<span id='error_message'>Only jpeg, jpg and png Images type allowed</span>";
}
else
{
var reader = new FileReader();
reader.onload = function(e) {
document.getElementById('preview').innerHTML = '';
document.getElementById('preview').innerHTML = '<img id="preview_img" src="' + e.target.result + '" alt="' + e.target.result + '">';
};
reader.readAsDataURL(image);
var dataString = "name=" + name + "&age=" + age + "&wpm=" + wpm + "&sex=" + sex + "&photo=" + image;
ajaxRequest.open("POST", "insert-example.php", true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.send(dataString);
document.getElementById('insertDiv').innerHTML = "processing...";
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4)
{
var insertDiv = document.getElementById('insertDiv');
insertDiv.innerHTML = ajaxRequest.responseText;
}
}
}
}
And here is the php that updates the localhost.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "";
$dbname = "ajaxtutorial";
$link = mysqli_connect($dbhost, $dbuser, $dbpassword, $dbname);
if (mysqli_connect_errno())
{
echo "Connection failed: %s" . mysqli_connect_error();
}
mysqli_connect($dbhost, $dbuser, $dbpassword) or die(mysql_error());
mysqli_select_db($link, $dbname) or die("Cannot connect to database");
$name = mysqli_real_escape_string($link, $_POST['name']);
$age = mysqli_real_escape_string($link, $_POST['age']);
$wpm = mysqli_real_escape_string($link, $_POST['wpm']);
$sex = mysqli_real_escape_string($link, $_POST['sex']);
// Image file code below
if (false)
{
$photo = $_FILES["photo"];
echo $photo;
}
else
{
echo var_dump($_FILES);
}
}
?>
The output I get from the var_dump is :
array (size=0)
empty
Could someone please tell me what is going wrong with my code?
Try to use jQuery, way more simple: (so replace everything in your js file with this script and keep the HTML and PHP)
$.ajax({
type: 'post',
url: 'update.php', //php script
data: new FormData($('form')[0]), //form data
processData: false,
contentType: false,
success: function (result) {
//do something cool when it is succesfully updated
});
PS: don't forget to include this BEFORE the script because it is jQuery: <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.2.min.js">
try this
var imageData = new FormData(image);
var dataString = "name=" + name + "&age=" + age + "&wpm=" + wpm + "&sex=" + sex + "&photo=" + imageData;
Sending files using a FormData object

How to solve PHP array with Json and Javascript

Can anybody help me with this problem ? I am trying to display the array that I retrieve from PHP in HTML / Java form.
<?php
header("Content-Type: application/json; charset=UTF-8");
require('routeros_api.class.php');
$API = new routeros_api();
$API->debug = true;
$API->connect('1.1.1.1', 'admin', '123');
$API->write('/ip/firewall/filter/print');
$READ = $API->read(false);
$ARRAY = $API->parse_response($READ);
echo json_encode ($ARRAY);
$API->disconnect();
?>
output
[{ ".id":"*6",
"chain":"unused-hs-chain",
"action":"passthrough",
"log":"false",
"disabled":"true"},
{ ".id":"*5",
"chain":"input",
"action":"accept",
"log":"false",
"disabled":"true"},
{ ".id":"*2A",
"chain":"unused-hs-chain",
"action":"drop",
"log":"false",
"disabled":"true"}]
displayjava.html
<tbody id="myTable">
<script>
var xmlhttp = new XMLHttpRequest();
var url = "testdata2.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 arr = JSON.parse(response);
var i;
var outp = "<tbody>";
for(i = 0; i < arr.length; i++) {
outp += "<tr>" +
"<td>" + arr[i].id + "</td>" +
"<td>" + arr[i].chain + "</td>" +
"<td>" + arr[i].action + "</td>" +
"<td>" + arr[i].log + "</td>" +
"<td>" + arr[i].disabled + "</td>" +
"</tr>";
}
outp += "</tbody>"
document.getElementById("myTable").innerHTML = outp;
}
</script>
</tbody>
By the way I am displaying the data in a table form format in html file
At least two problems there:
You're outputting invalid JSON:
[
{
"Name": "*6",
"City": "unused-hs-chain",
"City2": "unused-hs-chain",
"City3": "unused-hs- chain",
"Country": "passthrough"
}{
"Name": "*5",
"City": "input",
"City2": "input",
"City3": "input",
"Country": "accept"
}{
"Name": "*2A",
"City": "unused-hs-chain",
"City2": "unused-hs-ch
You need commas between those objects (after each } and before the next {).
Don't generate the JSON manually. Instead, just build up an array of what you want to send back in PHP, then use json_encode so it handles the details for you.
You're using properties on the objects in the array that aren't in the JSON. Your code usese arr[i].id, arr[i].chain, and arr[i].action, but the objects in your JSON don't have id, chain, or action properties, they have Name, City, City2, and so on.
Why not just use json_encode() instead of building it manually.
$output = array();
foreach($ARRAY as $rs) {
$output[] = array(
'Name' => $rs['id'],
'City' => $rs['chain'],
'City2' => $rs['chain'],
'City3' => $rs['chain'],
'Country' => $rs['action'],
);
}
echo json_encode($output);
exit;
Your JSON string response right now has missing {}, commas.
Don't build manually use json_encode() function ,
Above code is
<?php
header("Content-Type: application/json; charset=UTF-8");
require('routeros_api.class.php');
$API = new routeros_api();
$API->debug = true;
$API->connect('1.1.1.1', 'admin', '123');
$API->write('/ip/firewall/filter/print');
$READ = $API->read(false);
$ARRAY = $API->parse_response($READ);
$outp = array();
foreach($ARRAY as $rs) {
$outp[] = array(
'Name' => $rs['id'],
'City' => $rs['chain'],
'City2' => $rs['chain'],
'City3' => $rs['chain'],
'Country' => $rs['action'],
);
}
$API->disconnect();
echo json_encode($outp);
?>

Categories