Why is my code not passing to my div? - javascript

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

Related

Javascript : Uncaught SyntaxError: Unexpected token <

I have these code, which stores the php variable to a global javascript variable. All the modules are in same file, but still I get an Uncaught SyntaxError: Unexpected token <, at the rowNum1's line:-
<script type="text/javascript">
var glo = 0;
var rowNum = <?php echo $_GET['SN'];?>;
var newnames = new Array();
var rowNum1 = "";
var tempVal = "";
var destTextarea = "";
newnames=<?php echo json_encode($userinfoarr); ?>; //This varaible initialisation works fine
function fetchNext(){
if (glo++ === 0)
{
if(rowNum < newnames.length)
{
document.getElementById("Txt0").value = rowNum;
document.getElementById("Txt1").value = newnames[rowNum];
tempVal = newnames[rowNum];
}
rowNum++;
}
else
{
rowNum1=<?php echo json_encode($sln); ?>; //This one throws an Uncaught Syntax error
if(rowNum1 < newnames.length)
{
document.getElementById("Txt0").value = rowNum1;
document.getElementById("Txt1").value = newnames[rowNum1];
tempVal = newnames[rowNum1];
}
rowNum1++;
console.log("test");
}
}
</script>
This is the php code for $sln:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['Txt0']))
{
$sln = $_POST['Txt0'];
}
}
?>
This is the php code for $userinfoarr
<?php
require_once('config.php');
$result = mysqli_query($conn, "SELECT tweet from tweet");
$userinfoarr = array();
while ($row_user = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
$userinfo = $row_user["tweet"];
$push=array_push($userinfoarr, $userinfo);
}
?>
COuld anybody help me out with this, as I am unable here to understand the scenario?
Here is a screenshot of the error inside browser
change your php code as below. assign $sln default value
<?php
$sln = ""; //<---- assign default value to $sln
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['Txt0']))
{
$sln = $_POST['Txt0'];
}
}
?>
Do something like this
Modify $sln code as
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(isset($_POST['Txt0']))
{
$sln = $_POST['Txt0'];
echo "<script type='text/javascript'>var sln='$sln'</script>";
}
}
?>
and in script
{
rowNum1 = sln; //
if(rowNum1 < newnames.length)
{
document.getElementById("Txt0").value = rowNum1;
document.getElementById("Txt1").value = newnames[rowNum1];
tempVal = newnames[rowNum1];
}
rowNum1++;
console.log("test");
}
Use single quote for PHP code:
var rowNum = '<?php echo $_GET['SN'];?>';

excerpt(); function is not counting/working japanese words

I am working on Japanese language web site, and using this code for words limit, it is working when I paste English sentence but not working with Japanese words .
function content($num) {
$theContent = get_the_content();
$output = preg_replace('/<img[^>]+./','', $theContent);
$output = preg_replace( '/<blockquote>.*<\/blockquote>/', '', $output );
$output = preg_replace( '|\[(.+?)\](.+?\[/\\1\])?|s', '', $output );
$limit = $num+1;
$content = explode(' ', $output, $limit);
array_pop($content);
$content = implode(" ",$content)."...";
echo $content;
}
<?php content('15'); ?>
Can any body help me, and one thing is that I am using xeory_extension theme.
The problem is that Japanese characters are multibyte (Hiragana and Katakana characters are stored on 3 bytes in UTF-8), so you'll have to use special php multibytes string functions to manipulate strings that contains Japanese characters.
Sadly PHP doesn't provide a mb_explode function out of the box. Though some people worked on that, using mb_strlen and mb_substr to build up that missing function.
The following code is note mine, it comes from the fetus-hina mb_explode gist:
function mb_explode($delimiter, $string, $limit = -1, $encoding = 'auto') {
if(!is_array($delimiter)) {
$delimiter = array($delimiter);
}
if(strtolower($encoding) === 'auto') {
$encoding = mb_internal_encoding();
}
if(is_array($string) || $string instanceof Traversable) {
$result = array();
foreach($string as $key => $val) {
$result[$key] = mb_explode($delimiter, $val, $limit, $encoding);
}
return $result;
}
$result = array();
$currentpos = 0;
$string_length = mb_strlen($string, $encoding);
while($limit < 0 || count($result) < $limit) {
$minpos = $string_length;
$delim_index = null;
foreach($delimiter as $index => $delim) {
if(($findpos = mb_strpos($string, $delim, $currentpos, $encoding)) !== false) {
if($findpos < $minpos) {
$minpos = $findpos;
$delim_index = $index;
}
}
}
$result[] = mb_substr($string, $currentpos, $minpos - $currentpos, $encoding);
if($delim_index === null) {
break;
}
$currentpos = $minpos + mb_strlen($delimiter[$delim_index], $encoding);
}
return $result;
}
Then just use it the same way you use explode:
$content = mb_explode(' ', $output, $limit);
And for implode, you shouldn't have any issue.
This worked for me
function custom_short_excerpt($excerpt){
$limit = 200;
if (strlen($excerpt) > $limit) {
return substr($excerpt, 0, strpos($excerpt, ' ', $limit));
}
return $excerpt;
}
add_filter('the_excerpt', 'custom_short_excerpt');

Undefined offset 1: when passing a file using ajax file upload

When I pass data into my file upload controller, it is giving an error of undefined offset: 1.
function TestFileUpload() {
$i=0;
if(!isset($_FILES[$i]) ) {
echo "No file is being uploaded";
}
else {
$x = $_FILES[$i]['name'];
$xx = explode('.', $x);
$config['upload_path'] = 'MRS-files\Upload_files';
$config['allowed_types'] = 'xls|doc|jpg|png|gif|pdf';
$this->load->library('upload',$config);
$count = count($_FILES[$i]['name']). ' ';
while ($i <= 4 )
{
echo $count;
$x = $_FILES[$i]['name'];
$xx=explode(".", $x);
echo $_FILES[$i]['name'].' '.$_FILES[$i]['type'].' '.$_FILES[$i]['size'] ;
$this->upload->initialize($config);
$_FILES['up']['name'] = $_FILES[$i]['name'];
$_FILES['up']['tmp_name'] = $_FILES[$i]['tmp_name'];
$_FILES['up']['type'] = $_FILES[$i]['type'];
$_FILES['up']['size'] = $_FILES[$i]['size'];
if ( ! $this->upload->do_upload('up')) {
//error on uploading
echo str_replace('','',$this->upload->display_errors()); //temporary commented no use cause of redirect to homepage
//$this->cancelREC();
exit();
}
else{
$data = array('upload_data' => $this->upload->data());
$this->new_development_model->insertonAttachments($data['upload_data']);
$i++;
}
}
}
}
It's probably related cause you need to check in your loop if $_FILES[$i] is defined.
You do this but only one time, when $i = 0.
I even think that if you check in the loop, you wont need to do
if(!isset($_FILES[$i]) ) {
echo "No file is being uploaded";
}
else { /*...*/ }
before the loop

Trying to convert jQuery to prototype... jQuery causing issues

I have the following code:
<script type='text/javascript' src='js/jquery.js'></script>
<script type='text/javascript'>
var last_song = '$song[1]';
var jqy = jQuery.noConflict()
var change_radio = setInterval(function ()
{
jqy.ajax({
url : 'modules/ajax/refresh.php',
type : 'GET',
data : {lastsong: 'last_song'},
success: function(data)
{
last_song = data;
jqy('#radio').html(last_song);
}
});
}, ($refresh*1000));
change_radio;
</script>
refresh.php
<?php
$lastsong = $_GET['lastsong'];
$timeout = "2"; // Number of seconds before connecton times out.
$ip[1] = "198.101.13.110"; // IP address of shoutcast server
$port[1] = "8000"; // Port of shoutcast server
//$song = [];
//$msg = [];
//END CONFIGURATION
$servers = count($ip);
$i = "1";
while ($i <= $servers)
{
$fp = #fsockopen($ip[$i], $port[$i], $errno, $errstr, $timeout);
if (!$fp)
{
$listeners[$i] = "0";
$msg[$i] = "<span class=\"red\">ERROR [Connection refused / Server down]</span>";
$error[$i] = "1";
}
else
{
fputs($fp, "GET /7.html HTTP/1.0\r\nUser-Agent: Mozilla\r\n\r\n");
while (!feof($fp)) $info = fgets($fp);
$info = str_replace('<HTML><meta http-equiv="Pragma" content="no-cache"></head><body>', "", $info);
$info = str_replace('</body></html>', "", $info);
$stats = explode(',', $info);
if (empty($stats[1]))
{
$listeners[$i] = "0";
$msg[$i] = "<span class=\"red\">ERROR [There is no source connected]</span>";
$error[$i] = "1";
}
else
{
if ($stats[1] == "1")
{
$song[$i] = $stats[6];
$listeners[$i] = $stats[4];
$max[$i] = $stats[3];
// Both IFs the same? Please check that and make one only if its the case
if ($stats[0] == $max[$i]) $msg[$i] = "<span class=\"red\">";
if ($stats[0] == $max[$i]) $msg[$i] .= "</span>";
}
else
{
$listeners[$i] = "0";
$msg[$i] = " <span class=\"red\">ERROR [Cannot get info from server]</span>";
$error[$i] = "1";
}
}
}
$i++;
}
if($song[1] != "")
{
echo $song[1];
exit();
}
echo uriencode($lastsong);
?>
And I want to change it to use prototype instead. I use prototype and jQuery already, and this is conflicting as written. I've no idea where to begin, but any assistance would be appreciated... especially since there are a lot of folks in my situation. Thanks so much.

how to retrieve data through ajax?

I want a user to input a country, then it will output its population. My javascript is suppose to look up the country that the user input when the button is clicked, then goes through the PHP file and gets the country's population.
my HTML is:
<label>
Country:
<input name="country" type="text" id="country"></label>
<input type="button" value="Find population" id="findPop">
<p id="output"></p
and javascript:
var countryFound = function(data) {
var theCountry = $("#country").val();
var population = data["country"];
if (data["country"])
{
$("#output").html(theCountry + " population is " + population);
}
else {
$("#output").html(theCountry + " is not found");
}
};
$("#findPop").click(function(){
var theCountry = $("#country").val();
$("#output").html("Loading...");
$.getJSON("countrylookup.php", "country="+theCountry , countryFound);
});
my PHP code is:
if (isset($_GET['country'])) { // get the parameters country
$column = 'country';
$value = $_GET['country'];
else {
print -1; // an error code
return;
}
$data = array( 'country'=>'Peru', 'capital'=>'Lima', 'area'=>'1285220', 'population'=>'29907003', 'continent'=>'South America' ),
array( 'country'=>'Philippines', 'capital'=>'Manila', 'area'=>'300000', 'population'=>'99900177', 'continent'=>'Asia' );
function findData ( $whichColumn, $data, $searchValue)
{
$result = array();
foreach ($data as $row) {
if ($row[$whichColumn] == $searchValue)
$result[] = $row;
}
return $result;
}
print json_encode ( findData($column, $data, $value) );
but for some reason, when I input Peru as the country, it says Peru is not found. Am I not retrieving the correct data from the php or what? I'm pretty sure that my php code is correct.
Here's how I'd do it :
$(function() {
$("#findPop").on('click', function(){
var theCountry = $("#country").val();
$("#output").html("Loading...");
$.getJSON("countrylookup.php", {country: theCountry}, function(data) {
var population = data[0] != "false" ? data.population : false,
msg = population ? (" population is " + population) : " is not found";
$("#output").html(theCountry + msg);
});
});
});
PHP
$value = isset($_GET['country']) ? strtolower(trim($_GET['country'])) : false;
$result = false;
if ($value) {
$data = array(
'peru' => array(
'capital'=>'Lima',
'area'=>'1285220',
'population'=>'29907003',
'continent'=>
'South America'
),
'philippines' => array(
'capital'=>'Manila',
'area'=>'300000',
'population'=>'99900177',
'continent'=>'Asia'
)
);
if (array_key_exists($value, $data)) $result = $data[$value];
}
echo json_encode($result);
For the jQuery side, I recommend using the .get() function.
$("#findPop").click(function(){
var theCountry = $("#country").val();
$("#output").html("Loading...");
$.get("countrylookup.php", function(data) {
if(data) {
// Do whatever you want to do with the data, e.g.:
var population = data.population,
theCountry = $("#country").val();
// Do more magic
$("#output").html(theCountry = " population is " + population)
} else {
// Error handling
}
});
});
There is a } missing before the else in the fourth line of the PHP code.

Categories