Can't retrieve data from localhost tith ajax request and php script - javascript

I cannot retrieve the <p> elements that i echo in my php script. I'd like a solution / correction similar to mine because next to the data retrieve i have to style the <p> nodes with a javascript function. I'll be glad if my page doesn't refresh.
PHP:
<?php
$username = "root" ;
$database = "leaderboard" ;
$host = "localhost" ;
$connection = mysql_connect ( $host, $username ) or die ( "Impossibile stabilire connessione con il database della classifica!" .mysql_error() ) ;
mysql_select_db( $database ) or die ( "Impossibile trova il database!" .mysql_error() ) ;
if ( mysql_select_db( $database ) )
{
$SQL = "SELECT name, point FROM records ORDER BY point LIMIT 10"
$result = mysql_query($SQL);
$i = 0 ;
while ( $db_field = mysql_fetch_assoc($result) )
{
echo '<p id="echo"' + $i '>' + db_field[ 'name' ] ; + '. . . . ' + db_field[ 'punti' ] + '</p>' ;
$i = $i + 1 ;
}
}
else
{
print "Database NOT Found ";
}
mysql_close( $connection );
?>
Ajax request(i cannot use jQuery)
function leaderboard( oggetto )
{
alert ( " PROVO A LANCIARE LA RICHIESTA PER LA CLASSIFICA " ) ;
// Ajax sinc.
var http_request = new XMLHttpRequest() ;
http_request.open( "GET" , "./PhpScript/read_from_db.php?", false ) ;
http_request.send( null ) ;
// Here will come the style settings later
alert( document.getElementById( "echo0" ) ) ;
return ;
}
I'll be glad to recive a solution with no refreshing page, or an alternative way to solve the problem, both without jquery because of the project specs.

The quoting in your echo statement is wrong:
echo '<p id="echo"' + $i '>' + db_field[ 'name' ] ; + '. . . . ' + db_field[ 'punti' ] + '</p>' ;
should be:
echo '<p id="echo' . $i '">' . db_field[ 'name' ] ; . '. . . . ' . db_field[ 'punti' ] + '</p>' ;
$i has to be inside the quotes around the ID. And the concatenation operator in PHP is ., not +.

Related

ERR_CONNECTION_CLOSED - PHP and Javascript

The script below works perfectly when my site is without SSL, that is, with the domain http://www.dominio.com.br, but when I activate SSL for the site, it will be like https://www.dominio.com.br, Google Chrome displays the error "ERR_CONNECTION_CLOSED". But in firefox the error does not occur.
<?php
function redirecionaVariaveisCF7() {
?>
<script>
document.addEventListener( 'wpcf7mailsent', function( event ) {
if ( '4' == event.detail.contactFormId ) {
var inputs = event.detail.inputs;
for ( var i = 0; i < inputs.length; i++ ) {
if ( 'nome' == inputs[i].name ) {
var nome = inputs[i].value;
}
if ( 'email' == inputs[i].name ) {
var email = inputs[i].value;
}
}
window.location.href = 'testes/wp_01/teste-sucesso/?nome='+nome+'&email='+email;
}
}, false );
</script>
<?php
}
add_action( 'wp_footer', 'redirecionaVariaveisCF7' );
add_action( 'the_content', 'exibeVariaveisCF7' );
function exibeVariaveisCF7($cf7_exibe_mensagem_conteudo) {
if(is_page('teste-sucesso')){
$nome = htmlspecialchars($_GET["nome"]);
$email = htmlspecialchars($_GET["email"]);
?><script>
function cont(){
var conteudo = document.getElementById('boxImpressaoDisponivel').innerHTML;
tela_impressao = window.open('https://www.meudominio.com.br');
tela_impressao.document.write(conteudo);
tela_impressao.window.print();
tela_impressao.window.close();
}
</script><?php
$cf7_exibe_mensagem_txt = "<div class='container' id='boxImpressaoDisponivel'> <br> <center><img src='https://www.meudominio.com.br/testes/wp_01/wp-content/uploads/2019/03/logo.png' width='120'></center> <br><br><br>";
if ($nome != NULL){
$cf7_exibe_mensagem_txt .= "<b>Nome:</b> " . $nome ."<br>";
}
if ($email != NULL){
$cf7_exibe_mensagem_txt .= "<b>E-mail:</b> " . $email ."<br>";
}
$cf7_exibe_mensagem_txt .= "</div>";
$cf7_exibe_mensagem_txt .= "<div class='container'>";
$cf7_exibe_mensagem_txt .= "<input type='button' onclick='cont();' value='Imprimir'>";
$cf7_exibe_mensagem_txt .= "</div>";
}
$cf7_exibe_mensagem_resultado = $cf7_exibe_mensagem_txt . $cf7_exibe_mensagem_conteudo;
return $cf7_exibe_mensagem_resultado;
}
Google Chrome have strange behavior when switching between http/https. It has some kind of cache I think. There's nothing wrong with your PHP-script if it works in FF. So give Chrome some time...

Upload image with PHP and AngularJS

I am working on a admin panel which is going to add data on a SQLite DB using AngularJS and PHP and then show it in HTML. All good with data as arrays text date etc. The problem that I have is to upload an Image in a specified folder and store the path in my DB.
This is my PHP which store data in DB
<?php
try {
if (
empty($_POST['item']) ||
empty($_POST['description']) ||
empty($_POST['release']) ||
empty($_POST['demo']) ||
empty($_POST['type']) ||
empty($_POST['live']) ||
empty($_POST['client'])
) {
throw new PDOException("Invalid Request");
}
$item = $_POST['item'];
$description = $_POST['description'];
$release = $_POST['release'];
$demo = $_POST['demo'];
$type = $_POST['type'];
$live = $_POST['live'];
$client = $_POST['client'];
$objDb = new PDO('sqlite:../database/database');
$objDb->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO 'items'
('id', 'item', 'description', 'release', 'demo', 'type', 'live', 'client')
VALUES (null, ?, ?, ?, ?, ?, ?, ?)";
$statement = $objDb->prepare($sql);
if (!$statement->execute(array($item, $description, $release, $demo, $type, $live, $client))) {
throw new PDOException("The execute method failed");
}
And this is my PHP which upload Images in a specified folder
<?php
if (isset($_POST['submit'])) {
$validextensions = array("jpeg", "jpg", "png");
$temporary = explode(".", $_FILES["file"]["name"]);
$file_extension = end($temporary);
if ((($_FILES["file"]["type"] == "image/png") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/jpeg")
) && ($_FILES["file"]["size"] < 1000000)
&& in_array($file_extension, $validextensions)) {
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br/><br/>";
} else {
echo "<span>Your File Uploaded Succesfully...!!</span><br/>";
echo "<br/><b>File Name:</b> " . $_FILES["file"]["name"] . "<br>";
echo "<b>Type:</b> " . $_FILES["file"]["type"] . "<br>";
echo "<b>Size:</b> " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "<b>Temp file:</b> " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " <b>already exists.</b> ";
} else {
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]);
echo "<b>Stored in:</b> " . "upload/" . $_FILES["file"]["name"];
}
}
} else {
echo "<span>***Invalid file Size or Type***<span>";
}
}
?>
And this is my insert function from angular
$scope.insert = function() {
if ($scope.goodToGo()) {
var thisData = "item=" + $scope.item;
thisData += "&description=" + $scope.description;
thisData += "&release=" + $scope.release;
thisData += "&demo=" + $scope.demo;
thisData += "&client=" + $scope.client;
thisData += "&type=" + $scope.type;
thisData += "&live=" + $scope.live;
thisData += "&image=" + $scope.image;
$http({
method : 'POST',
url : urlInsert,
data : thisData,
headers : {'Content-Type' : 'application/x-www-form-urlencoded'}
})
.success(function(data){
if(_recordAddedSuccessfully(data)){
$scope.items.push({
id : data.item.id,
item : data.item.item,
description : data.item.description,
release : data.item.release,
demo : data.item.demo,
client : data.item.client,
client_name : data.item.client_name,
type : data.item.type,
type_name : data.item.type_name,
live : data.item.live,
live_name : data.item.live_name,
image : data.item.image,
done : data.item.done
});
$scope.clear();
}
})
.error(function(data, status, headers, config){
throw new Error('Something went wrong with inserting');
});
}
};
Have anyone any idea how to do this?
If you are uploading image then content type should be set to multipart/form-data i.e
headers : {'Content-Type' : 'multipart/form-data'}
rest looks fine.

A way to merge td's in a table

So I'm trying to create a weekly calendar.
I coded a loop in javascript creating the empty table and then afterwards modified the innerHTML of the appropriate td's from values taken from an SQL table using php and javascript.
My problem is that when I set the rowspan of the specific td instead of merging with the next td's it is moving them to the end of my table. If I have 2 more reputation points i will post pictures to show my problem.
Here is my code if you want to take a look at it
// Declare usefull information about the database and host
$mysql_host = "-host info-";
$mysql_database = "-database info-";
$mysql_user = "user";
$mysql_password = "pass";
// open the connection
$link = mysql_connect($mysql_host,$mysql_user, $mysql_password, $mysql_database);
// connect to the database
mysql_select_db($mysql_database, $link) or die('database not selected'. mysql_error());
// Select * from the table created in the database
$result = mysql_query("SELECT * FROM Appointment;")
or die("Could not query:" . mysql_error());
echo "<script type='text/javascript' > "
. "var hours = new Array('9:00','9:30','10:00','10:30','11:00','11:30', "
. "'12:00','12:30','13:00','13:30','14:00','14:30','15:00','15:30');"
. ""
. "var days = new Array('Mon','Tue','Wed','Thu','Fri','Sat');"
. ""
. "for ( i = 0; i < 14 ; i++ ) "
. "{"
. "document.write('<tr id='+hours[i]+':00'+'>');"
. "document.write('<th>'+ hours[i]+'</th> '); "
." for ( k = 0 ; k < 6; k++)"
."{"
. "document.write('<td id='+days[k] +'> </td>'); "
. "}"
. "document.write('</tr>');"
."}"
. " </script> ";
while( $row = mysql_fetch_array( $result ))
{
$timestamp = strtotime($row['Date']);
$day = date('D', $timestamp);
$from = $row['StartTime'];
$to = $row['EndTime'];
$rowspan = determinRowSpanBetween($from,$to);
echo "<script type='text/javascript'> "
. " var divToAddTo = GetElementInsideContainer('".$from."','".$day."');"
. "divToAddTo.className = 'busy';"
. "divToAddTo.rowspan='".$rowspan."';"
. "divToAddTo.innerHTML='Something to do';"
. "function GetElementInsideContainer(containerID, childID) {"
. " var elm = {};"
. " var elms = document.getElementById(containerID).getElementsByTagName('*');"
. " for (var i = 0; i < elms.length; i++) {"
. " if (elms[i].id === childID) {"
. " elm = elms[i];"
. " break;"
. " }"
. "}"
. "return elm;"
. "}"
. " </script>" ;
}
the function determinRowSpanBetween is created later on in the code.
Having a rowspan > 1 in a td that is only supposed to take up one space (i.e. one that is not merged with other td's) will cause a whole bunch of errors. Make sure you account for every row you add to rowspan.

Loading tables of different dimensions in infinite scroll page while minimizing empty space between tables

I have a website where users contribute with content. The content takes form of tables, where every td element is of equal height and width. The different pieces of content have different number of rows and columns. I want to stack these elements in an infinite-scroll webpage. ATM I'm doing this: I construct a table, in it a tr. I load element by element inside tds and count their number of columns. When a certain threshold has been reached, i break the tr and start a new tr. This makes the content elements border eachother sideways, leaving no room between each. However I also want to load the elements in such a way that there is minimal room between elements vertically. How can I do this?
Here is my code. I DO NOT expect to have it rewritten or have new code written for me. This is only to make it clearer to you what I am currently doing.
<?php
$row = 0;
$column = 0;
$maxColumns = 124;
echo "<table><tr>";
$listHandle = fopen('pieces/piecesList', 'r');
while (!feof($listHandle)) {
echo "<td>";
$filename = trim(fgets($listHandle));
$templateHandle = fopen("pieces/" . $filename, 'r');
$thisLine = fgets($templateHandle);
list($lowestX, $highestX, $lowestY, $highestY) = sscanf($thisLine, '%d %d %d %d');
//echo $lowestX . $highestX . $lowestY . $highestY;
$templateTable = "<table id=\"" . $filename . "\" title =\"" . $filename . "\">" . PHP_EOL;
$greenCells = array();
$fileLength = 0;
while (!feof($templateHandle)) {
$thisLine = fgets($templateHandle);
list($thisX, $thisY) = sscanf($thisLine, '%d %d');
$carrier = $thisX . " " . $thisY;
array_push($greenCells, $carrier);
$fileLength++;
}
for ($y = $lowestY; $y <= $highestY; $y++) {
// echo "inside for loop Y \n";
$templateTable = $templateTable . "<tr>" . PHP_EOL;
for ($x = $lowestX; $x <= $highestX; $x++) {
// echo $y . $x;
$templateTable = $templateTable . "<td";
$coordinateExists = FALSE;
for ($i = 0; $i < $fileLength; $i++) {
if ($greenCells[$i] == $x . " " . $y) {
$coordinateExists = TRUE;
break;
}
}
if ($coordinateExists) {
$templateTable = $templateTable . " class=\"green";
if ($x == 0 && $y == 0) {
$templateTable = $templateTable . " markerdot";
}
$templateTable = $templateTable . "\"";
} else if ($x == 0 && $y == 0) {
$templateTable = $templateTable . " class=\"markerdot\"";
}
$templateTable = $templateTable . " x='" . $x . "' y='" . $y . "'>";
$templateTable = $templateTable . "</td>" . PHP_EOL;
}
$templateTable = $templateTable . "</tr>" . PHP_EOL;
}
$templateTable = $templateTable . "</table> </td>";
if ($column == 0) {
$tallestTemplateHeight = $highestY - $lowestY;
} else if (($highestY - $lowestY) > $tallestTemplateHeight) {
$tallestTemplateHeight = $highestY - $lowestY;
}
echo $templateTable;
$column += $highestX - $lowestX;
if ($column >= $maxColumns) {
$row += $tallestTemplateHeight;
echo "</tr></table><table><tr>";
}
}
fclose($listHandle);
?>
</div>
PS: I am open to discarding my current setup entirely.
I'll throw this out as an idea - FIDDLE
It uses divs instead of a table, and by playing with the loops, width, etc, you can adjust it as you see fit.
Everything fits together edge to edge.
JS
var counter = 0;
var numdivs = 8;
$('#clickme').click(function(){
for(var i=1; i < 50; ++i)
{
$("<div class='standarddiv'>X</div>").appendTo('.holder');
counter = counter + 1;
if(counter==numdivs)
{
$("<div class='clearboth'></div>").appendTo('.holder');
counter = 0;
}
}
});

Getting buddypress user name in a javascript file

From within my buddypress PHP templates I usually get the username of any given user by referencing the user ID like this:-
<?php echo bp_core_get_username( '{{userID}}' ) ?>
However I need to retrieve the username from within an external Javascript file.
The user ID is already passed in as var aData[11]. I have tried the following with no luck:-
$('td:eq(3)', nRow).html( '<div class="table-row"><h4 class="nomargin">' + aData[0] + '</h4>' + aData[1] + '</div>' );
I am trying to return a URL... This cirrently gives me:
http://www.mysite.com/members//song/?songsID=6
Whe it should be:
http://www.mysite.com/members/username/song/?songsID=6
Any ideas?
Edit: Below is the server side code that I am using to ouput the JSON
<?php
$aColumns = array( 'song_name', 'artist_band_name', 'author', 'song_artwork', 'song_file', 'genre', 'song_description', 'uploaded_time', 'emotion', 'tempo', 'songsID', 'user' );
$sIndexColumn = "songsID";
/* DB table to use */
$sTable = "wp_dbt_songs";
/* Database connection information */
$gaSql['user'] = "";
$gaSql['password'] = "";
$gaSql['db'] = "";
$gaSql['server'] = "";
$gaSql['link'] = mysql_pconnect( $gaSql['server'], $gaSql['user'], $gaSql['password'] ) or
die( 'Could not open connection to server' );
mysql_select_db( $gaSql['db'], $gaSql['link'] ) or
die( 'Could not select database '. $gaSql['db'] );
$sLimit = "";
if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
{
$sLimit = "LIMIT ".mysql_real_escape_string( $_GET['iDisplayStart'] ).", ".
mysql_real_escape_string( $_GET['iDisplayLength'] );
}
if ( isset( $_GET['iSortCol_0'] ) )
{
$sOrder = "ORDER BY ";
for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
{
if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
{
$sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
".mysql_real_escape_string( $_GET['sSortDir_'.$i] ) .", ";
}
}
$sOrder = substr_replace( $sOrder, "", -2 );
if ( $sOrder == "ORDER BY" )
{
$sOrder = "";
}
}
$sWhere = "";
if ( $_GET['sSearch'] != "" )
{
$sWhere = "WHERE (";
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string( $_GET['sSearch'] )."%' OR ";
}
$sWhere = substr_replace( $sWhere, "", -3 );
$sWhere .= ')';
}
/* Individual column filtering */
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
{
if ( $sWhere == "" )
{
$sWhere = "WHERE ";
}
else
{
$sWhere .= " AND ";
}
$sWhere .= $aColumns[$i]." LIKE '%".mysql_real_escape_string($_GET['sSearch_'.$i])."%' ";
}
}
$sQuery = "
SELECT SQL_CALC_FOUND_ROWS ".str_replace(" , ", " ", implode(", ", $aColumns))."
FROM $sTable
$sWhere
$sOrder
$sLimit
";
$rResult = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
/* Data set length after filtering */
$sQuery = "
SELECT FOUND_ROWS()
";
$rResultFilterTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
$aResultFilterTotal = mysql_fetch_array($rResultFilterTotal);
$iFilteredTotal = $aResultFilterTotal[0];
/* Total data set length */
$sQuery = "
SELECT COUNT(".$sIndexColumn.")
FROM $sTable
";
$rResultTotal = mysql_query( $sQuery, $gaSql['link'] ) or die(mysql_error());
$aResultTotal = mysql_fetch_array($rResultTotal);
$iTotal = $aResultTotal[0];
$output = array(
"sEcho" => intval($_GET['sEcho']),
"iTotalRecords" => $iTotal,
"iTotalDisplayRecords" => $iFilteredTotal,
"aaData" => array()
);
while ( $aRow = mysql_fetch_array( $rResult ) )
{
$row = array();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if ( $aColumns[$i] == "version" )
{
/* Special output formatting for 'version' column */
$row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
}
else if ( $aColumns[$i] != ' ' )
{
/* General output */
$row[] = $aRow[ $aColumns[$i] ];
}
}
$output['aaData'][] = $row;
}
echo json_encode( $output );
?>
The html you're setting is being set on the client side, not on the server side, meaning that the php code will not be evaluated.
I guess what you can do is either put the already-evaluated username in a hidden tag and get that using jquery or expose it to the javascript on the page within script tags.
EDIT: So is the userID or the username in the json as well? If not, you could probably put it there. I'm still not so sure what the situation is. But if you're currently passing the userID in the json and actually want the username as bp_core_get_username would return it, why not just put the already retrieved (with bp_core_get_username) username into the json as well?
In other words, in your php code, figure out what the username is based on the userid with bp_core_get_username and then pass that into the json. That is, if I'm understanding the situation correctly.

Categories