JSON php MySql menu not showing data in HTML page - javascript

I'm trying to populate a drop-down menu from a MySql.
My problem is that the data from JASON are not showing in my HTML page.
This is what I want to achieve.
ID: Select ID
JASON //This works and the output: {"article1":{ "title":"acGH2867" },"article2":{ "title":"apGS0158" }}
$jsonData = '{';
foreach ($conn_db->query("SELECT customerID FROM customers WHERE furniture='33' ") as $result){
$i++;
$jsonData .= '"article'.$i.'":{ "title":"'.$result['customerID'].'" },';
}
$jsonData = chop($jsonData, ",");
$jsonData .= '}';
echo $jsonData;
HTML
<script type="text/javascript">
$(document).ready(function(){
var ddlist = document.getElementById("ddlist");
var hr = new XMLHttpRequest();
hr.open("cData.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var d = JSON.parse(hr.responseText);
for(var o in d){
if(d[o].title){
ddlist.innerHTML += '</option><option value='+d[o].title+'</option>';
}
}
}
}
ddlist.innerHTML = "Loading....";
$('#dlist').on('change', function(){
$('#val1').value() = $(this).val();
});
});
</script>
</head>
<div class="dlist" id="ddlist">
</div>

try this
$jsonData = array();
foreach ($conn_db->query("SELECT customerID as title FROM customers WHERE furniture='33' ") as $result)
{
$i++;
$jsonData["article'.$i]=$result;
}
echo json_encode($jsonData);

Related

Having trouble sending AND receiving information from a php file using javascript

I am sending some information to a php file that runs a query but I want to also retrieve some information from that php file at the same time. The php file executes fine but I can't get the json_encoded object.
Javascript function that sends a string and a number to a php file:
function open_close(){
var status = encodeURIComponent(SelectedTicket["Status"]);
var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
var info = "Status="+status+"&TicketNum="+ticketNum;
var http3 = createAjaxRequestObject();
if (http3.readyState == 4) {
if (http3.status == 200){
alert("Ticket Updated!"); //This never gets hit
getUpdatedTicket(JSON.parse(http3.responseText));
}
}
http3.open("POST", "openClose.php", true);
http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http3.send(info);
}
PHP File that takes the string and number and updates a table
<?php
include("config.php");
session_start();
$status = $_POST["Status"];
$num = $_POST["TicketNum"];
$newStatus = " ";
if(strcmp($status, "Open") == 0){
$newStatus = "Closed";
}
elseif(strcmp($status, "Closed") == 0){
$newStatus = "Open";
}
$sql = "UPDATE tickets SET Status = \"$newStatus\" where TicketNum = $num ";
$r = $conn ->query($sql) or trigger_error($conn->error."[$sql]");
$sql = "SELECT * FROM tickets where TicketNum = $num";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$data[] = $row;
}
echo json_encode($data);
?>
How can I retrieve the json_encoded object in the same javascript function?
You'd need a readyState listener to know when the request is done, and then get the data from the responseText
function open_close() {
var status = encodeURIComponent(SelectedTicket["Status"]);
var ticketNum = encodeURIComponent(SelectedTicket["TicketNum"]);
var info = "Status=" + status + "&TicketNum=" + ticketNum;
var http3 = createAjaxRequestObject();
http3.onreadystatechange = function () {
if (http3.readyState == 4) {
if (http3.status == 200) {
console.log(http3.responseText); // <- it's there
}
}
}
http3.open("POST", "openClose.php", true);
http3.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http3.send(info);
}

How to pass value to the second page using Javascript AJAX

I have an html select on my page
<pre>
$query = mysql_query("select * from results");
echo "<select id='date' onchange='showdata()' class='form-control'>";
while ($arr = mysql_fetch_array($query)) {
echo "<option value=".$arr['month'].">".$arr['month']." / ".$arr['year']. "</option>" ;
}
echo "</select>";
</pre>
the options are coming from database. After this I have ajax script
<script>
function showdata() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "result.php", true);
xhttp.send();
}
</script>
I want it to send the selected value in the html select to the page result.php
another way of doing the same thing using jquery ajax ...
<select id="item" onchange="send_item(this.value)">
<?php $someVariable = $_GET["someVariable"];
$query = mysql_query("select * from results");
echo "";
while ($arr = mysql_fetch_array($query)) {?>
<option value="<?php echo your value?>"><?php echo your value?></option>
<?php }?>
</select>
<script>
function send_item(str){
$.ajax({
url: '',
type: "post",
data: {
'str':str,
},
success: function(data) {
},
});
}
</script>
Try with this:
$someVariable = $_GET["someVariable"];
$query = mysql_query("select * from results");
echo "";
while ($arr = mysql_fetch_array($query)) {
echo "".$arr['month']." / ".$arr['year']. "" ;
}
echo "";
And JS:
<script>
function showdata() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "result.php?someVariable=test", true);
xhttp.send();
}
</script>
If you need example for POST, visit Send POST data using XMLHttpRequest

Having json inside autocomplete

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);
}
?>

New variable ajaxObj does not work

For some weird reason this line of code is not working:
var ajax = ajaxObj("POST", "php_parsers/status_system.php");
What could it be?
I figured it must be the above line using window.alert's since after that line window.alert does not run.
Full code:
The function is called:
$status_ui = '<textarea id="statustext" onkeyup="statusMax(this,250)" placeholder="What's new with you '.$u.'?"></textarea>';
$status_ui .= '<button id="statusBtn" onclick="postToStatus(\'status_post\',\'a\',\''.$u.'\',\'statustext\')">Post</button>';
The function:
function postToStatus(action,type,user,ta){
window.alert("status passed 1");
var data = _(ta).value;
if(data == ""){
alert("Type something first weenis");
return false;
}
window.alert("status passed 2");
_("statusBtn").disabled = true;
var ajax = ajaxObj("POST", "php_parsers/newsfeed_system.php");
window.alert("status passed 3");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "post_ok"){
var sid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
var currentHTML = _("statusarea").innerHTML;
_("statusarea").innerHTML = '<div id="status_'+sid+'" class="status_boxes"><div><b>Posted by you just now:</b> <span id="sdb_'+sid+'">delete status</span><br />'+data+'</div></div><textarea id="replytext_'+sid+'" class="replytext" onkeyup="statusMax(this,250)" placeholder="write a comment here"></textarea><button id="replyBtn_'+sid+'" onclick="replyToStatus('+sid+',\'<?php echo $u; ?>\',\'replytext_'+sid+'\',this)">Reply</button>'+currentHTML;
_("statusBtn").disabled = false;
_(ta).value = "";
} else {
alert(ajax.responseText);
}
}
}
ajax.send("action="+action+"&type="+type+"&user="+user+"&data="+data);
window.alert("status passed 4");
}
newsfeed_system.php
if (isset($_POST['action']) && $_POST['action'] == "status_post"){
// Make sure post data is not empty
if(strlen($_POST['data']) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Make sure type is a
if($_POST['type'] != "a"){
mysqli_close($db_conx);
echo "type_unknown";
exit();
}
// Clean all of the $_POST vars that will interact with the database
$type = preg_replace('#[^a-z]#', '', $_POST['type']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Insert the status post into the database now
$sql = "INSERT INTO newsfeed(author, type, data, postdate)
VALUES('$log_username','$type','$data',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
mysqli_query($db_conx, "UPDATE newsfeed SET osid='$id' WHERE id='$id' LIMIT 1");
mysqli_close($db_conx);
echo "post_ok|$id";
exit();
}
Ajax methods:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
Please help!
The ajax is not refrenced! You need to include the library or put the code for calling an 'ajaxObj'.

Why is my code not passing to my div?

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();
}
?>

Categories