How come autocomplete doesnt work when I got json data that has items in it? I can se that it is becoming a list, but it is not filling with names.
Example of my json data: http://nettport.com/no/stram/search.php?term=e
<script>
$(function() {
$( "#inp_meal_a_0" ).autocomplete({
source: 'search.php'
});
$('#inp_meal_a_0').on('autocompleteselect', function (e, ui) {
var val = $('#inp_size_a_0').val();
var energy = ui.item.energy;
var proteins = ui.item.proteins;
var carbohydrates = ui.item.carbohydrates;
var fat = ui.item.fat;
$("#inp_energy_a_0").val((energy*val)/100);
$("#inp_proteins_a_0").val((proteins*val)/100);
$("#inp_carbs_a_0").val((carbohydrates*val)/100);
$("#inp_fat_a_0").val((fat*val)/100);
});
});
</script>
Search.php
<?php
header('Content-type: text/html; charset=windows-1252;');
// Make a MySQL Connection
$host = $_SERVER['HTTP_HOST'];
if($host == "127.1.1.0"){
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("n") or die(mysql_error());
}
// Quote smart
function quote_smart($value){
// Stripslashes
if (get_magic_quotes_gpc() && !is_null($value) ) {
$value = stripslashes($value);
}
//Change decimal values from , to . if applicable
if( is_numeric($value) && strpos($value,',') !== false ){
$value = str_replace(',','.',$value);
}
if( is_null($value) ){
$value = 'NULL';
}
// Quote if not integer or null
elseif (!is_numeric($value)) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
if(isset($_GET['term']) && $_GET['term'] != ''){
$term = $_GET['term'];
$term = strip_tags(stripslashes($term));
$term = trim($term);
$term = strtolower($term);
$term = $term . "%";
$part_mysql = quote_smart($term);
//get matched data from skills table
$x = 0;
$query = "SELECT cc_id, cc_food_name, cc_manufactor_name, cc_serving_size, cc_serving_mesurment, cc_energy, cc_proteins, cc_carbohydrates, cc_fat FROM stram_calorie_calculation WHERE cc_food_name LIKE $part_mysql";
$r = mysql_query($query);
while ($row = mysql_fetch_array($r, MYSQL_NUM)) {
$get_cc_id = $row[0];
$get_cc_food_name = $row[1];
$get_cc_manufactor_name = $row[2];
$get_cc_serving_size = $row[3];
$get_cc_serving_mesurment = $row[4];
$get_cc_energy = $row[5];
$get_cc_proteins = $row[6];
$get_cc_carbohydrates = $row[7];
$get_cc_fat = $row[8];
if($get_cc_food_name == ""){
$result = mysql_query("DELETE FROM stram_calorie_calculation WHERE cc_id='$get_cc_id'") or die(mysql_error());
}
$data[$x] = array('food_name' => $get_cc_food_name, 'energy' => $get_cc_energy, 'proteins' => $get_cc_proteins, 'carbohydrates' => $get_cc_carbohydrates, 'fat' => $get_cc_fat);
//$data[$x] = $get_cc_food_name;
$x++;
}
//return json data
echo json_encode($data);
}
?>
Related
I'm trying to display a json array with contents from my database but when their is accents in the database the json array doesn't want to be displayed, their is my code:
<?php
include 'connect.php';
header('Content-Type: text/plain; charset=UTF-8') ;
$serial = 1;
$statment = mysqli_prepare($conn, "SELECT * FROM lesson WHERE serial = ?");
mysqli_stmt_bind_param($statment, "i", $serial);
mysqli_stmt_execute($statment);
mysqli_stmt_store_result($statment);
mysqli_stmt_bind_result($statment, $serial, $by, $type, $description, $lesson, $nb_q);
$response = array();
$response["success"] = false;
while(mysqli_stmt_fetch($statment)){
$response["success"] = true;
$response["serial"] = $serial;
$response["by"] = $by;
$response["type"] = $type;
$response["lesson"] = $lesson;
$response["description"] = $description;
$response["nb_q"] = $nb_q;
for ($i = 1; $i <= $nb_q; $i++) {
$statment2 = mysqli_prepare($conn, "SELECT * FROM question WHERE 4_l_id = ? AND q_num = ?");
mysqli_stmt_bind_param($statment2, "ii", $serial, $i);
mysqli_stmt_execute($statment2);
mysqli_stmt_store_result($statment2);
mysqli_stmt_bind_result($statment2, $question, $nb_answer, $type, $correct_1, $for_l_id, $id, $q_num);
while(mysqli_stmt_fetch($statment2)){
$response["q".$i] = $question;
}
}
}
echo json_encode($response, JSON_UNESCAPED_UNICODE);
?>
Thank you for your answers
I found a good code but thank you for your help,
<?php
include 'connect.php';
$serial = 1;
$statment = mysqli_prepare($conn, "SELECT * FROM lesson WHERE serial = ?");
mysqli_stmt_bind_param($statment, "i", $serial);
mysqli_stmt_execute($statment);
mysqli_stmt_store_result($statment);
mysqli_stmt_bind_result($statment, $serial, $by, $type, $description, $lesson, $nb_q);
$response = array();
$response["success"] = false;
function utf8_encode_all(&$value)
{
if (is_string($value)) return utf8_encode($value);
if (!is_array($value)) return $value;
$ret = array();
foreach($dat as $i=>$d) $ret[$i] = utf8_encode_all($d);
return $ret;
}
while(mysqli_stmt_fetch($statment)){
$response["success"] = true;
$response["serial"] = $serial;
$response["by"] = utf8_encode_all($by);
$response["type"] = utf8_encode_all($type);
$response["lesson"] = utf8_encode_all($lesson);
$response["description"] = utf8_encode_all($description);
$response["nb_q"] = $nb_q;
for ($i = 1; $i <= $nb_q; $i++) {
$statment2 = mysqli_prepare($conn, "SELECT * FROM question WHERE 4_l_id = ? AND q_num = ?");
mysqli_stmt_bind_param($statment2, "ii", $serial, $i);
mysqli_stmt_execute($statment2);
mysqli_stmt_store_result($statment2);
mysqli_stmt_bind_result($statment2, $question, $nb_answer, $type, $correct_1, $for_l_id, $id, $q_num);
while(mysqli_stmt_fetch($statment2)){
$response["q".$i] = utf8_encode_all($question);
}
}
}
$array = array_map('htmlentities',$response);
$json = html_entity_decode(json_encode($array));
echo $json;
?>
So I've got my password being passed to a php page and returning json data
However if it returns nothing. nothing happings. My Failed login never fires. Can someone tell what I'm doing wrong.
<script>
$(document).ready(function(){
var password = "";
//PRESSING AN INPUT KEY
$('.sixPinInput').keyup(function (k) {
if (this.value.length == this.maxLength) {
password = password+this.value;
password = password.substring(0,6);
$(this).next('.sixPinInput').focus();
$(".pinIncorrectMessage").css("display", "block");
$(".pinIncorrectMessage").html(password);
}
//PRESSING DELETE
if (k.keyCode == 8) {
$(this).prev().val("").focus();
password = password.slice(0, -1);
$(".pinIncorrectMessage").html(password);
}
});
//PRESSING LAST INPUT KEY
$("#f").keyup(function() {
if($("#f").val().length > 0) {
$.post("http://heber/QC/includes/getUserInfo.php", {user: password}, function(data, status) {
//IF SUCCESSFUL LOGIN
password = "";
$(".sixPinInput").val("");
if(data) {
$(data).each(function(index, value) {
alert(value.firstName + value.lastName)
$(".cover").fadeOut(200);
$(".sixPinInputContainer").fadeOut(200);
$("#pageBody").css("overflow", "scroll");
})
}
//IF FAILED LOGIN
if(!data) {
$(".cover").fadeOut(200);
$(".sixPinInputContainer").fadeOut(200);
$("#pageBody").css("overflow", "scroll");
}
})
}
})
});
</script>
And this is my PHP
<?php include "db.php"; ?>
<?php
if (isset($_POST['user'])) {
$password = $_POST['user'];
$query = $connect->prepare("
SELECT firstName, lastName, color1, color2, authorizationLevel FROM employee WHERE password = ? LIMIT 1");
if(!$query) {
echo "Query Failed because " . mysqli_error($connect);
}
$query->bind_param("s", $password);
$query->execute();
$result = $query->get_result();
if ($result) {
while($row = mysqli_fetch_assoc($result)) {
$firstName = $row['firstName'];
$lastName = $row['lastName'];
$color1 = $row['color1'];
$color2 = $row['color2'];
$authorizationLevel = $row['authorizationLevel'];
session_start();
$_SESSION['firstName'] = $firstName;
$_SESSION['lastName'] = $lastName;
$_SESSION['color1'] = $color1;
$_SESSION['color2'] = $color2;
$_SESSION['authorizationLevel'] = $authorizationLevel;
$array[] = array (
'firstName'=>$firstName,
'lastName'=>$lastName,
'color1'=>$color1,
'color2'=>$color2,
'authorizationLevel'=>$authorizationLevel
);
}
header('Content-type: application/json');
echo json_encode($array);
}
}
?>
I'm trying to create a gameserver query for my website, and I want it to load the content, save it, and echo it later. However, it doesn't seem to be echoing. It selects the element by ID and is supposed to echo the content of the VAR.
Here's my HTML code:
<center><div id="cstrike-map"><i class="fa fa-refresh fa-spin"></i> <b>Please wait ...</b><br /></div>
JavaScript:
<script type="text/javascript">
var map = "";
var hostname = "";
var game = "";
var players = "";
$.post( "serverstats-cstrike/cstrike.php", { func: "getStats" }, function( data ) {
map = ( data.map );
hostname = ( data.hostname );
game = ( data.game );
players = ( data.players );
}, "json");
function echoMap(){
document.getElementByID("cstrike-map");
document.write("<h5>Map: " + map + "</h5>");
}
</script>
PHP files:
query.php
/* SOURCE ENGINE QUERY FUNCTION, requires the server ip:port */
function source_query($ip)
{
$cut = explode(":", $ip);
$HL2_address = $cut[0];
$HL2_port = $cut[1];
$HL2_command = "\377\377\377\377TSource Engine Query\0";
$HL2_socket = fsockopen("udp://".$HL2_address, $HL2_port, $errno, $errstr,3);
fwrite($HL2_socket, $HL2_command); $JunkHead = fread($HL2_socket,4);
$CheckStatus = socket_get_status($HL2_socket);
if($CheckStatus["unread_bytes"] == 0)
{
return 0;
}
$do = 1;
while($do)
{
$str = fread($HL2_socket,1);
$HL2_stats.= $str;
$status = socket_get_status($HL2_socket);
if($status["unread_bytes"] == 0)
{
$do = 0;
}
}
fclose($HL2_socket);
$x = 0;
while ($x <= strlen($HL2_stats))
{
$x++;
$result.= substr($HL2_stats, $x, 1);
}
$result = urlencode($result); // the output
return $result;
}
/* FORMAT SOURCE ENGINE QUERY (assumes the query's results were urlencode()'ed!) */
function format_source_query($string)
{
$string = str_replace('%07','',$string);
$string = str_replace("%00","|||",$string);
$sinfo = urldecode($string);
$sinfo = explode('|||',$sinfo);
$info['hostname'] = $sinfo[0];
$info['map'] = $sinfo[1];
$info['game'] = $sinfo[2];
if ($info['game'] == 'garrysmod') { $info['game'] = "Garry's Mod"; }
elseif ($info['game'] == 'cstrike') { $info['game'] = "Counter-Strike: Source"; }
elseif ($info['game'] == 'dod') { $info['game'] = "Day of Defeat: Source"; }
elseif ($info['game'] == 'tf') { $info['game'] = "Team Fortress 2"; }
$info['gamemode'] = $sinfo[3];
return $info;
}
cstrike.php
include('query.php');
$ip = 'play1.darkvoidsclan.com:27015';
$query = source_query($ip); // $ip MUST contain IP:PORT
$q = format_source_query($query);
$host = "<h5>Hostname: ".$q['hostname']."</h5>";
$map = "<h5>Map: ".$q['map']."</h5>";
$game = "<h5>Game: ".$q['game']."</h5>";
$players = "Unknown";
$stats = json_encode(array(
"map" => $map,
"game" => $game,
"hostname" => $host,
"players" => $players
));
You need to display the response in the $.post callback:
$.post( "serverstats-cstrike/cstrike.php", { func: "getStats" }, function( data ) {
$("#map").html(data.map);
$("#hostname").html(data.hostname);
$("#game").html(data.game);
$("#players").html(data.players);
}, "json");
You haven't shown your HTML, so I'm just making up IDs for the places where you want each of these things to show.
There are some things that I can't understand from your code, and echoMap() is a bit messed up... but assuming that your php is ok it seems you are not calling the echomap function when the post request is completed.
Add echoMap() right after players = ( data.players );
If the div id you want to modify is 'cstrike-map' you could use jQuery:
Change the JS echoMap to this
function echoMap(){
$("#cstrike-map").html("<h5>Map: " + map + "</h5>");
}
So what I did was I had to echo the content that I needed into the PHP file, then grab the HTML content and use it.
That seemed to be the most powerful and easiest way to do what I wanted to do in the OP.
<script type="text/javascript">
$(document).ready(function(){
$.post("stats/query.cstrike.php", {},
function (data) {
$('#serverstats-wrapper-cstrike').html (data);
$('#serverstats-loading-cstrike').hide();
$('#serverstats-wrapper-cstrike').show ("slow");
});
});
</script>
PHP
<?php
include 'query.php';
$query = new query;
$address = "play1.darkvoidsclan.com";
$port = 27015;
if(fsockopen($address, $port, $num, $error, 5)) {
$server = $query->query_source($address . ":" . $port);
echo '<strong><h4 style="color:green">Server is online.</h4></strong>';
if ($server['vac'] = 1){
$server['vac'] = '<img src="../../images/famfamfam/icons/tick.png">';
} else {
$server['vac'] = '<img src="../../images/famfamfam/icons/cross.png">';
}
echo '<b>Map: </b>'.$server['map'].'<br />';
echo '<b>Players: </b>'.$server['players'].'/'.$server['playersmax'].' with '.$server['bots'].' bot(s)<br />';
echo '<b>VAC Secure: </b> '.$server['vac'].'<br />';
echo '<br />';
} else {
echo '<strong><h4 style="color:red">Server is offline.</h4></strong>';
die();
}
?>
I want to make an ajax request on click with jquery, but it's not working:
This is what I have:
The button:
$photos_box .= '<a id="' . $imgID . '" class="like_button">' . $like . '</a>';
Maybe there's an error in the script:
// Like function
$('.like_button').click(function() {
$(this).toggleClass('liked');
var status = '';
if ($(this).hasClass('liked')) {
status = 'like';
$(this).html('Ya no me gusta');
console.log('like_works');
} else {
status = 'unlike';
$(this).html('Me gusta');
console.log('unlike_works');
}
var data = {
img_id : this.id,
sta : status
};
$.ajax({
type : 'POST',
url : '/includes/like.php',
data : data
}).done(function(reslike) {
if (reslike == 1) console.log('ajax_works');
});
});
And this is the like.php file:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
sec_session_start();
// User id
if (login_check($mysqli) == true) {
$user_id = $_SESSION['user_id'];
}
$img_id = $_POST['img_id'];
$status = $_POST['sta'];
$stmt = $mysqli->prepare("SELECT * FROM img_likes WHERE img_id = ? AND user_id = ?");
$stmt->bind_param("ii", $img_id, $user_id);
$stmt->execute();
$result = $stmt->get_result();
$usr_likes = $result->num_rows;
if ($status == 'like') {
if ($usr_likes == 0) {
$stmt->close();
$stmt = $mysqli->prepare("INSERT INTO img_likes (img_id, user_id) VALUES(?, ?)");
$stmt->bind_param("ii", $img_id, $user_id);
$stmt->execute();
}
}
else if ($status == 'unlike') {
if ($usr_likes != 0) {
$stmt->close();
$stmt = $mysqli->prepare("DELETE FROM img_likes WHERE img_id = ? AND user_id = ?");
$stmt->bind_param("ii", $img_id, $user_id);
$stmt->execute();
}
}
}
At last! Thanks to everyone. Hope my code help someone.
Check the URL in your ajax request, I'm not certain but I don't think '../includes/like.php' is a valid URL I think you actually have to give it a valid server URL like "http://example.com/includes/like.php"
My problem now when I click on the picture on my page, for the first time it will display. But for the second time it will display fail. This process will start by sending the data to ajax, then ajax(prosess.js) will send it to the php page(process1.php).
When I remove the code in blockquote ($query = "SELECT ...") it will run, but if not, it will display fail.
process1.php
<?php
include 'session.php';
include 'connection.php';
if(isset($_POST['dataS'])) {
$table = $_POST['table'];
$concat = "";
$serial = $_POST['dataS'];
$query = "SELECT * FROM product WHERE serialNum = '$serial'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
if($row) {
$prodName = $row['prodName'];
$quanProd = 1;
$priceProd = $_POST['total'] + $row['salePrice'];
if($table == "") {
$query = "SELECT * FROM product WHERE serialNum = '$serial'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
}
else{
$DOM = new DOMDocument;
$DOM->loadHTML($table);
$items = $DOM->getElementsByTagName('tr');
$check = 0;
$check_one = 0;
$y=0;
function tdrows($elements,$check,$serial,$prodName,$y) {
$quantity="";
$item = "";
$price = "";
$delete = "";
$x = 0;
foreach($elements as $element) {
if($x == 0)
$delete = $element->nodeValue;
else if($x == 1)
$item = $element->nodeValue;
else if($x == 2)
$quantity = $element->nodeValue;
else if($x == 3)
$price = $element->nodeValue;
$x++;
}
**$query = 'SELECT prodName FROM product WHERE prodName = "$item"';
$search = mysqli_query($conn, $query) or die(mysqli_error());
$row = mysqli_fetch_assoc($search);
$s = $row['prodName'];**
if($prodName == $s) {
$quantity++;
$check = 1;
}
else {
$check = 0;
}
return $check;
}
foreach ($items as $node) {
$check = tdrows($node->childNodes,$check,$serial,$prodName,$y);
$y++;
}
}
$priceProd = number_format((float)$priceProd, 2, '.', '');
echo json_encode (
array ( //this array is used to send the data back to ajax.
"success" => "1",
"concat" => $concat,
"quantity" => $quanProd,
"price" => $priceProd,
)
);
}
else {
echo json_encode (
array ( //this array is used to send the data back to ajax.
"success" => "0",
)
);
}
}
?>
process.js
$(document).ready(
function() {
$("body").on("click","#product .add",
function(e) {
var total = document.getElementById("total").value;
var table = document.getElementById('table-list').innerHTML;
table = (table.trim) ? table.trim() : table.replace(/^\s+/,'');
var serial = $(this).attr('id');
var totalQ = document.getElementById("totalQ").value;
if(total == "")
total = 0;
else
total = parseFloat(total);
if(totalQ == "")
totalQ = 0;
else
totalQ = parseInt(totalQ);
var dataS = serial;
e.preventDefault();
$.ajax({
type : "POST",
url : "process1.php",
crossDomain: true,
data : {dataS : dataS, table : table, total : total},
dataType : 'json',
})
.done(function(html) {
if(html.success == 1) {
console.log('done: %o', html);
$("#table-list").html(html.concat).show();
document.getElementById('totalQuantity').innerHTML = html.quantity;
document.getElementById("total").value = html.price;
document.getElementById("payment").value = html.price;
document.getElementById('totalQ').value = html.quantity;
document.getElementById('title').innerHTML = html.price;
document.getElementById('input').value='';
$("#input").focus();
}
else {
alert("Wrong serial number!");
document.getElementById('input').value='';
$("#input").focus();
}
})
.fail(function(html) {
console.info('fail: %o', html);
alert("fail");
});
return false;
});
});
connection.php
<?php
$conn = mysqli_connect('localhost','root','','rds');
?>
your query is wrong:try this
$query = "SELECT prodName FROM product WHERE prodName = '".$item."'";
According to your pictures, your problem is that your database connection isn't correct. When you execute the first request it won't do any database interaction (because off the blocknotes). The second request you will send table data, which will perform a query. So the first request will succeed, while the second request will give you an error on your mysqli ($conn) object.
if($table == "") {
//Database interaction
$query = "SELECT * FROM product WHERE serialNum = '$serial'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
}
else{
//No database interaction because of the blocknotes
$DOM = new DOMDocument;
$DOM->loadHTML($table);
$items = $DOM->getElementsByTagName('tr');
$check = 0;
$check_one = 0;
$y=0;
function tdrows($elements,$check,$serial,$prodName,$y) {
$quantity="";
$item = "";
$price = "";
$delete = "";
$x = 0;
foreach($elements as $element) {
if($x == 0)
$delete = $element->nodeValue;
else if($x == 1)
$item = $element->nodeValue;
else if($x == 2)
$quantity = $element->nodeValue;
else if($x == 3)
$price = $element->nodeValue;
$x++;
}
**$query = 'SELECT prodName FROM product WHERE prodName = "$item"';
$search = mysqli_query($conn, $query) or die(mysqli_error());
$row = mysqli_fetch_assoc($search);
$s = $row['prodName'];**
if($prodName == $s) {
$quantity++;
$check = 1;
}
else {
$check = 0;
}
return $check;
}
foreach ($items as $node) {
$check = tdrows($node->childNodes,$check,$serial,$prodName,$y);
$y++;
}
}
Check your the username, password and database name. I'm pretty sure you used something wrong here. As mentioned in your connection.php file you don't use a password. Are you sure the user root doens't have a password? Can you access the database with a MySQL administration tool like phpMyAdmin?