I am trying to make an incredibly simple ajax call, but it wont work.
Here is the php side called by ajax( This returns the correct response )
<?php
$returnValue = '';
$allUploads = array_slice(scandir('./uploads'), 2);
$returnValue .= '<table>';
foreach ($allUploads as $upload) {
$returnValue .= '<tr><a href ="/uploads/' . $upload . '>' . $upload . '</a></tr>';
}
$returnValue .= '</table>';
echo($returnValue);
?>
And here is the javascript thats letting me down
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange =
function ()
{
if (this.readyState == 4 && this.status == 200)
{
alert(this.responseText);
document.getElementById("filedisplaytable").innerHTML = this.responseText;
}
};
xhttp.open("GET", "listuploads.php", true);
xhttp.send();
</script>
Worst thing about this is, that the alert statement is outputting exactly what I want to write:
<table>
<tr>
<a href ="/uploads/DSC001.jpg>DSC001.jpg</a></tr><tr><a href ="/uploads/DSC002.jpg>DSC002.jpg</a>
</tr>
<tr>
<a href ="/uploads/DSC003.jpg>DSC003.jpg</a>
</tr>
</table>
But when I write that into the div it writes the a hrefs 1st followed by an empty table...
Any help is greatly appreciated.... struggling to do such simple things really gets me down
Your HTML is invalid.
An <a> element cannot be a child element of a <tr>.
Only <td> and <th> are allowed there.
The problem you are experiencing is likely the result of the browser attempting to recover from your error by moving the <a> elements to somewhere they are allowed (i.e. outside the table).
Write valid HTML instead. It looks like you don't have a tabular data structure so probably shouldn't be using a table in the first place. A list might be a better bet.
Like Quentin said, your HTML is invalid. <a> tags are allowed in <td> though.
Replace your PHP line of code with this one:
$returnValue .= '<tr><td><a href ="/uploads/' . $upload . '>' . $upload . '</a></td></tr>';
Related
I need the id in url to make a mysql_query. The problem is that I need to make this from an Ajax call and $_GET['id'] apparently is not working.
Is there an easy way to free myself from this?
Thank you :)
Here is my ajax call:
echo "<div id='loading_utilizadores' class='loading'><img src='".$CONF['HOME']."/images/structure/ajax-loader.gif'/></div>";
echo "<div id='utilizadores'></div>";
echo "<script type='text/javascript'>";
echo "CarregaAjax(\"#utilizadores\",\"#loading_utilizadores\",\"".$CONF['HOME']."/superadmin/box_utilizadores_ajax.php\", \"GET\")";
echo "</script>";
The ajax function:
function CarregaAjax(id,loading,page,method){
if(method=="GET"){
$(document).ready(function(){
//$(loading).ajaxStart(function(){
$(loading).show();
$(id).hide();
//});
$(id).load(page);
$(loading).ajaxStop(function(){
$(loading).hide();
$(id).show();
});
});
}
else{
$(document).ready(function(){
//$(method).submit(function() {
$(loading).show();
$(id).load(page,$(method).serializeArray());
$(loading).hide();
return false;
//});
});
}
And the peace of html ajax call. In this page I try to make the $_GET['id'], but with no success.
if (isset($_GET['id']))
{
$officeID = intval($_GET['id']);
}
else
{
$officeID = 0;
}
if(!isset($crm_users))$crm_users = new crm_utilizadores;
//$officeID = 12;
$resultGetUsers = $crm_users->getUsersByOfficeId($officeID);
$html = "<table class='table1' width='100%' cellpadding='5' cellspacing='1' border='0'>";
if(!empty($resultGetUsers)){
$html .= "<tr>";
$html .= "<td class='table_title1'>Utilizador</td>";
$html .= "<td class='table_title1'>Telefone</td>";
$html .= "<td class='table_title1'>Telemóvel</td>";
$html .= "<td class='table_title1'>E-mail</td>";
$html .= "<td class='table_title1'>Situação</td>";
$html .= "</tr>";
}else{
$html .= "<tr><td class='empty1'>não foram encontrados utilizadores registados neste cliente</td></tr>";
}
//finalizar a tabela
$html .= "</table>";
I guess I'm mising the point, right? :p
This code attempts to read the id value from the URL:
$_GET['id']
But this is the URL you're requesting:
/superadmin/box_utilizadores_ajax.php
As you can see, there is no id value (or any other value). That would look something like this instead:
/superadmin/box_utilizadores_ajax.php?id=123
The value has to be on the URL in order for $_GET to read it.
Now, the page you're currently viewing may have that value in the URL you previously requested. But the server-side code isn't looking at your screen or interacting with your web browser. All it knows is the request that you send it. And that request doesn't contain that value.
You can, when loading the page, put that value on the request. In index.php read the $_GET['id'] value and output it to the JavaScript code which is making that AJAX request. Technically it could be something as simple as this, just to demonstrate:
"/superadmin/box_utilizadores_ajax.php?id=" . $_GET['id'] . "\", \"GET\")"
However, be aware of the dangers of outputting raw user input to the page. This results in things like XSS vulnerabilities. Be mindful of what you're outputting to the page, but ultimately you need to output that value somewhere in order for that JavaScript code to send it to the next (AJAX) request. (Or, alternatively, you could store the file server-side in session state or something similar. Thereby removing the URL from the equation entirely. There are pros and cons either way.)
In short, you need to include the value on the URL being requested if the page at that URL is going to read the value. The code can only read values which are there.
I have an html file that contains a table with table rows
<table style="width:auto">
<tr>
<td contenteditable="true"><select id="so"></select></td>
</tr>
</table>
I have a PHP that selects from mySQL DB and returns username
if ($results->num_rows > 0) {
// output data of each row
while($row = $results->fetch_assoc()) {
$name=$row["first_name"];
echo "<option>
$name
</option>";
}
} else {
echo "0 results";
}
I am trying to incorporate the result of the php into my index.html file within the table so that the option shows up in the table
How can I get the data from PHP into an already built html table row?
Any help would be appreciated.
Two way to get the job done:-
1)Use a class, that is you should, and using its object you can retrieve the data and use it on the webpage .
ex:- see this class, it needs a lot of improvements and changes, but still can give you some idea . I am also trying to learn PDO well, not a PRO, but can be helpful to you.Comments on this class will help you get the idea .
2)Using AJAX, You can request for this data on loading the document or you can request it via get, post, request.. on any event.If you know ajax, you can use that class and ajax, or if you do not have an idea about AJAX, you can get a lot of resources to learn ajax. after this if you need my assistant, I will try to help you.
for this work you should use ajax to load data in html file ...
you can do it with javascript :
create a function for load your php file :
function loadAjax(address,elementId) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById(elementId).innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", address, true);
xhttp.send();
}
after create it you can use it when you want (for example after load of page). you should pass address of your php file and id of html element that you want the answer load into it .
for more learn :
http://www.w3schools.com/ajax/
There are couple of methods that can be used here. If the HTML and PHP are in the same file you could do this:
<?php
if ($results->num_rows > 0) {
$options = ''; // declare the variable to hold the options
// output data of each row
while($row = $results->fetch_assoc()) {
$name=$row["first_name"];
$options .= "<option>$name</option>"; // add the options to the variable
}
} else {
$options = "0 results";
}
?>
And then add the $options to the HTML:
<table style="width:auto">
<tr>
<td contenteditable="true">
<select id="so">
<?php echo $options; ?>
</select>
</td>
</tr>
</table>
Another option, though not as neat, is to embed the PHP in the HTML:
<table style="width:auto">
<tr>
<td contenteditable="true">
<select id="so">
<?php
if ($results->num_rows > 0) {
// output data of each row
while($row = $results->fetch_assoc()) {
$name=$row["first_name"];
echo "<option>
$name
</option>";
}
} else {
echo "0 results";
}
?>
</select>
</td>
</tr>
</table>
Yet another option would be to use AJAX to call the PHP from the HTML page and return the results to the right location. For instance, if you wanted to use jQuery you could follow a tutorial to learn the basics and then apply that to your code.
I want to refresh two variables named profittext and sumtext which will be refreshed and echoed in the following places every few seconds. I know AJAX is needed to do this but how do i actually make it work ? The only way i found out was to refresh the content of the whole file. is there any way to refresh specific variables? Any answers will be greatly appreciated . Thank you very very much.
<table>
if($profitandloss<$zero) {
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
} elseif ($profitandloss>$zero) {
$profitText = "<div style=\"color: green;\">$profitandloss</div>";
}
// for profit and loss counting
$sum+= $profitandloss;
//
echo "<tr><td>" . $row['trade_id'] .
"</td><td>" . $row['selection'] .
"</td><td>" . $row['date'] .
"</td><td>" . $row['type'] .
"</td><td>" . $row['size'] .
"</td><td>" . $row['bidprice'] .
"</td><td>" . $row['offerprice'] .
"</td><td>" . $row['stoploss'] .
"</td><td>" . $row['takeprofit'] .
"</td><td>" . $profitText .
"</td><td><a href ='delete.php?id=".
$row['trade_id']."'>X</a>
</td></tr>";
$profitandloss=0;
if($sum<$zero) {
$sumText = "<div style=\"color: red;\">$sum</div>";
} elseif ($sum>$zero) {
$sumText = "<div style=\"color: green;\">$sum</div>";
}
}
echo "</table><br>";
?>
<!DOCTYPE html>
<html>
<table style="border:1px solid black;">
<tr>
<th style="border:1px solid black;">Profit/Loss</th>
</tr>
<tr>
<td style="border:1px solid black;"><?php echo $sumText ;?></td>
</tr>
</table>
</html>
I struggled with the concept of how to structure such code when I first started too. Although it's not specific to your particular variables, here's a quick example for how to update a var through AJAX with jQuery/PHP.
Prologue: If this is something you're going to be doing often, you'll want to learn jQuery, rather than using normal javascript alone. There are lots of great, free, resources on how to learn jQuery. Alternatively, if you're not satisfied with the free tutorials online, this is an excellent book. I'll write the example in jQuery.
Design: Okay, so the way it works is this:
Set a timer in javascript to execute a particular function every X seconds (you DO NOT want to do it every second).
That function makes an AJAX call (with jQuery) to a .PHP file on the server, sending it the data necessary so that the .PHP code knows what to send back.
The .PHP code grabs the data required (e.g., with MySQL) encodes it in a JSON format, and exits.
A promise on the AJAX call is fired and the data sent from PHP is received. Process it as you will.
Repeat from step 2.
If you have any questions about what the code is doing, please ask.
AJAX.PHP
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$return_obj = array();
$request_obj = NULL;
// our AJAX call used "POST" as it's 'type', so we look in that
// variable.
if ( array_key_exists("func",$_POST) ) {
if ( $_POST['func'] === "get_update" ) {
if ( array_key_exists("which_var",$_POST) ) {
$which_var = $_POST['which_var'];
$which_var = $mysqli->real_escape_string($which_var); // should use prepared statements
// we sent 'num_people_logged_in' as our value here, so we'll be looking for a column/field
// with that value. this assumes that some other code, somewhere else,
// is regularly updating the table. it also assumes that there will only
// be a single row returned, which will hold the value.
$query = "SELECT '$which_var' FROM site_stats ";
if ( $result = $mysqli->query($query) ) {
if ( $row = $result->fetch_assoc() ) {
$request_obj[$which_var] = $row[$which_var];
}
}
}
}
}
$return_obj['request'] = $request_obj;
echo json_encode($return_obj);
die();
?>
MYCODE.JS
// this actually sends the AJAX request to the server.
function getUpdate() {
var jqXHR = $.ajax({
url : "ajax.php",
data : {
'func' : 'get_update',
'which_var' : 'num_people_logged_in'
},
dataType : 'json',
type : 'POST',
timeout : 10000
});
// attach 'promises' to the jqXHR object, which represents
// the AJAX call itself. 'promises' are, in this context,
// just events.
jqXHR.done(function(data,textStatus,jqXHR) {
// this executes if the AJAX call succeeded.
// the variable 'data' holds what the server
// sent us.
if ( ( data ) && ( data.request ) ) {
receiveUpdate(data.request);
}
});
jqXHR.fail(function(jqXHR,textStatus,errorThrown) {
// this executes if it failed
console.log("Fail: " + textStatus + " (" + errorThrown + ")");
});
jqXHR.always(function(a,textStatus,c){
// this executes either way, after .done or .fail
});
}
// this is called from jqXHR.done, on success
function receiveUpdate(request_obj) {
if ( request_obj.num_people_logged_in ) {
updateDOM(request_obj.num_people_logged_in);
}
}
function updateDOM(num_people_logged_in) {
if ( num_people_logged_in ) {
$("#mydiv > p.update").html("The updated value is: " + num_people_logged_in);
}
}
var timeoutID = null;
// setup our timer, to periodically make an
// AJAX call
function init() {
timeOutID = setInterval(function(){
getUpdate();
},5000);
}
// stop the timer
function cleanup() {
clearTimeout(timeoutID);
}
INDEX.HTML
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>AJAX practice</title>
<!-- <link href="mycss.css" rel='stylesheet'> if needed -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="mycode.js"></script>
<script>
$(document).ready(function() {
init();
$("#cleanup").on("click",function(){
cleanup();
});
}); // end ready
</script>
</head>
<body>
<div id='mydiv'>
<p>
How many people are online?
</p>
<p class='update'>
</p>
</div>
<button id='cleanup'>Stop updating!</button>
</div>
</body>
</html>
You will needd two PHP pages:
- one with HTML and JS, which periodicly makes ajax calls and puts the result to the HTML
- second with json (or even plain text) output of your dynamic data piece
Unfortunately, writing the full code in the answer is not someting that people do at stackoverflow, so just look at small example below, and try to figure out the missing parts.
http://jsfiddle.net/AMEqz/
var xhr = new XMLHttpRequest();
xhr.onload = function(r) {
// your render logic HERE
setTimeout(send, 1000);
}
function send() {
xhr.open("GET", "/", true);
xhr.send();
}
send();
p.s.: keep in mind that each ajax request will mean extra connection to your server, so make sure it can deal with the load ;)
Use a timer : https://developer.mozilla.org/en/docs/DOM/window.setInterval
setInterval(function(){
//update your var here
},1000);
Im looking to create a condition in wordpress loop. if no image then image box (.thumbHome{display:none})
this is in my function.php
function getThumbImages($postId) {
$iPostID = get_the_ID();
$arrImages =& get_children('post_type=attachment&post_mime_type=image&post_parent=' . $iPostID );
if($arrImages) {
$arrKeys = array_keys($arrImages);
$iNum = $arrKeys[0];
$sThumbUrl = wp_get_attachment_thumb_url($iNum, $something);
$sImgString = '<img src="' . $sThumbUrl . '" alt="thumb Image" title="thumb Image" />';
echo $sImgString;}
else {
echo '<script language="javascript">noImage()</script>';
}
}
And my javascript:
window.onload = noImage();
function noImage(){
document.getElementByClassName('.thumbHome').css.display = 'none';
}
I tried:
window.onload = noImage();
function noImage(){
$('.thumbHome').addClass('hide');
}
RESULT: class hide added to all loop
I cant figure it another way, since im still new in coding.
thx
Well first of all, you don't want to call these functions on window.onload. That's going to immediately set all class instances of .thumbHome to hidden without any conditions.
Here's a very easy way to fix this issue. There are probably more intricate ways, but this works well.
In your main loop, add an unique id to each .thumbHome div based on the image id. So like:
echo '<div class="thumbHome" id="thumb-' . $iNum . '"> ... </div>';
// or you could you use the post ID, doesn't matter, as long as you are consistent
Then your else conditional (for whether there's a thumbnail) could be changed to:
else {
echo '<script type="text/javascript">noImage("#thumb-' . $iNum . '")</script>';
}
and your js function could be:
function noImage(var){
$(var).hide();
}
This is not necessary the best way to do this, it's just the best way with the situtation you find yourself in now.
<?php } elseif($_SOMETHING == 1 && $_ANOTHER_THING == 2) { ?>
<?php $_NAME = urlencode($_NAME); ?>
<?php $_MGT_NAME = urlencode($_MGT_NAME); ?>
</div>
<?php } ?>
I am getting this error expected ';'
The horror. The horror.
Here's the actual error, in the onclick attribute value:
lpButtonCTTUrl = 'http:...Ad%20Source=somesite.com& ='+escape(document.location); imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>&referrer
That is, there should be a +' instead of ; after the document.location inclusion, and there should be a closing quote after the imageURL inclusion, and referrer is in the wrong place (it should be just before the document.location inclusion.
It also has problems like the use of escape (never use escape. For URL-encoding you actually want encodeURLComponent); the unescaped ampersands all over the place; and the lack of HTML- and URL-encoding of values output from PHP, potentially causing cross-site scripting risks.
Writing a value inside a URL component inside a URL inside a JavaScript string literal inside an attribute value inside HTML is utter insanity so it's no surprise there are mistakes. Let's try to bring some maintainability to this madness. Break out the JavaScript and URL creation into separate steps where getting the escaping right is possible.
function urlencodearray($a) {
$o= array();
foreach ($a as $k=>$v)
array_push($o, rawurlencode($k).'='.rawurlencode($v));
return implode('&', $o);
}
function h($s) {
echo htmlspecialchars($s);
}
With these utility functions defined, then:
<?php } elseif($_SOMETHING == 1 && $_ANOTHER_THING == 2) { ?>
<?php
$lpbase= 'http://server.iad.liveperson.net/hc/84152841/?';
$linkurl= $lpbase.urlencodearray(array(
'cmd'=>'file',
'file'=>'visitorWantsToChat',
'site'=>'84152841',
'byhref'=>'1',
'skill'=>'somesiteILS',
'SESSIONVAR!skill'=>'somesiteILS',
'SESSIONVAR!Management Company'=>$_MGT_NAME,
'SESSIONVAR!Community'=>$_NAME,
'SESSIONVAR!Ad%20Source'=>'somesite.com',
'imageUrl'=>"http://{$_SERVER['SITENAME']}/images/"
));
$imgurl= $lpbase.urlencodearray(array(
'cmd'=>'repstate',
'site'=>'84152841',
'channel'=>'web',
'ver'=>'1',
'skill'=>'somesiteILS',
'imageUrl'=>"http://{$_SERVER['SITENAME']}/images/"
));
?>
<div id="caller_tag">
<a id="_lpChatBtn" target="chat84152841" href="<?php h($url); ?>">
<img src="<?php h($imgurl); ?>" name="hcIcon" alt="Chat" border="0">
</a>
<script type="text/javascript">
document.getElementById('_lpChatBtn').onclick= function() {
var url= this.href+'&referrer='+encodeURIComponent(location.href);
if ('lpAppendVisitorCookies' in window)
url= lpAppendVisitorCookies(url);
if ('lpMTag' in window && 'addFirstPartyCookies' in lpMTag)
url= lpMTag.addFirstPartyCookies(url)
window.open(url, this.target, 'width=475,height=400,resizable=yes');
return false;
};
</script>
</div>
With an unformatted mess like that it's no wonder you can't find the error.
I tried running it through HTML Tidy but it doesn't like anything between the comments.
mesite.com& ='+escape(document.location); imageUrl=<?php print "ht
I'm not good at reading long lines like that but shouldn't this be
mesite.com& ='+escape(document.location) +'imageUrl=<?php print "ht
First of: why are you opening and closing PHP so many times, you could write it like:
<?php
} elseif($_SOMETHING == 1 && $_ANOTHER_THING == 2) {
$_NAME = urlencode($_NAME);
$_MGT_NAME = urlencode($_MGT_NAME);
?>
<div id="caller_tag">
<!-- BEGIN LivePerson Button Code --><a id="_lpChatBtn" href='http://server.iad.liveperson.net/hc/84152841/?cmd=file&file=visitorWantsToChat&site=84152841&byhref=1&SESSIONVAR!skill=somesiteILS&SESSIONVAR!Management%20Company=<?php print $_MGT_NAME; ?>&SESSIONVAR!Community=<?php print $_NAME; ?>&SESSIONVAR!Ad%20Source=somesite.com&imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>' target='chat84152841' onClick="lpButtonCTTUrl = 'http://server.iad.liveperson.net/hc/84152841/?cmd=file&file=visitorWantsToChat&site=84152841&SESSIONVAR!skill=somesiteILS&SESSIONVAR!Management%20Company=<?php print $_MGT_NAME; ?>&SESSIONVAR!Community=<?php print $_NAME; ?>&SESSIONVAR!Ad%20Source=somesite.com& ='+escape(document.location); imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>&referrer lpButtonCTTUrl = (typeof(lpAppendVisitorCookies) != 'undefined' ? lpAppendVisitorCookies(lpButtonCTTUrl) : lpButtonCTTUrl); lpButtonCTTUrl = ((typeof(lpMTag)!='undefined' && typeof(lpMTag.addFirstPartyCookies)!='undefined')?lpMTag.addFirstPartyCookies(lpButtonCTTUrl):lpButtonCTTUrl);window.open(lpButtonCTTUrl,'chat84152841','width=475,height=400,resizable=yes');return false;" ><img src='http://server.iad.liveperson.net/hc/84152841/?cmd=repstate&site=84152841&channel=web&&ver=1&imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>&skill=somesiteILS' name='hcIcon' alt='Chat Button' border=0></a><!-- END LivePerson Button code -->
</div>
And also: the error must be somewhere else, I can't see a missing ";" in php in the code you pasted, unless the error is in javascript.